[Python-Dev] Context management patterns

Xavier Morel python-dev at masklinn.net
Sat Oct 19 15:53:49 CEST 2013


On 2013-10-19, at 08:38 , Nick Coghlan wrote:
>> The above example, especially if extended beyond two files, begs to used in
>> a loop, like your 5 line version:
>> 
>> 
>> for name in ("somefile.tmp", "someotherfile.tmp"):
>>       with suppress(FileNotFoundError):
>>                os.remove(name)
>> 
>> which would be fine, of course.
>> 
>> But to some with less education about the how and why, it is not clear why
>> it couldn't be written like:
>> 
>> with suppress(FileNotFoundError):
>> 
>>        for name in ("somefile.tmp", "someotherfile.tmp"):
>>                os.remove(name)
>> 
>> yet to the cognoscenti, it is obvious there are seriously different
>> semantics.
> 
> However, that's a confusion about exception handling in general, not
> about the suppress context manager in particular. The same potential
> for conceptual confusion exists between:
> 
>    for name in ("somefile.tmp", "someotherfile.tmp"):
>        try:
>            os.remove(name)
>        except FileNotFoundError:
>            pass
> 
> and:
> 
>    try:
>        for name in ("somefile.tmp", "someotherfile.tmp"):
>           os.remove(name)
>    except FileNotFoundError:
>        pass

It could work if the exceptions system was extended to a full-blow
conditions system though.


More information about the Python-Dev mailing list