correct way to catch exception with Python 'with' statement

Matt Wheeler m at funkyhat.org
Tue Nov 29 20:17:38 EST 2016


On Tue, 29 Nov 2016 at 23:59 <woooee at gmail.com> wrote:

> If you want to do something only if the file exists (or does not), use
> os.path.isfile(filename)
>

This opens you up to a potential race condition (and has potential security
implications, depending on the application), as you're using LBYL[0].
If you want to write robust code, you'll need to catch the
FileNotFoundError anyway, so unless you're doing many* file lookups and
expecting a large number of them* to not exist, you're probably better off
with EAFP[1] unless you're really sure (i.e. you've followed the 3 rules of
performance optimisation[2])


*I'm being quite vague here as you'd have to actually profile the
application to work out which way is quicker and if the difference is worth
worrying about.
Catching the exception in theory might be more expensive, but that cost
might be insignificant compared to the IO cost which you'll have either way.

[0] https://docs.python.org/2/glossary.html#term-lbyl
[1] https://docs.python.org/2/glossary.html#term-eafp
[2] http://wiki.c2.com/?RulesOfOptimization



More information about the Python-list mailing list