Granularity of OSError

MRAB python at mrabarnett.plus.com
Sat Sep 19 16:10:54 CEST 2009


Grant Edwards wrote:
> On 2009-09-19, Christian Heimes <lists at 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.



More information about the Python-list mailing list