Grant Edwards wrote:
On 2009-09-19, Christian Heimes <li...@cheimes.de> wrote:
kj wrote:
For example, LBYL would look like this:

if os.path.isfile(some_file):
    os.unlink(some_file)

In contrast, EAFP would look like this:

try:
    os.unlink(some_file)
except OSError:
    pass

The two version aren't equal. The first one suffers from a race
condition which may lead to a severe security issue. The file may be
gone or replaced by a different file in the time span between the check
and the call to unlink().

IOW, just be cause you look before you leap, it doesn't mean
you're not going to land on anybody and have to ask for
forgiveness afterwards.

Since you always have to handle the error case, there's not
much point in checking first unless the error case has bad
side-effects that you're trying to avoid.  In this case,
attempting to unlink a non-existent file has no bad
side-effects, so there's no point in checking before the
unlink.

It doesn't mean that LBYL is always a bad idea. If, for example, you're
going to copy a file, it's a good idea to check beforehand that there's
enough space available for the copy. There might be other process
changing the amount of freespace available, but it's still a reasonable
check to do.
--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to