correct way to catch exception with Python 'with' statement

Marko Rauhamaa marko at pacujo.net
Wed Nov 30 07:23:31 EST 2016


Marko Rauhamaa <marko at pacujo.net>:

> Peter Otten <__peter__ at web.de>:
>
>> Marko Rauhamaa wrote:
>>>    try:
>>>        f = open("xyz")
>>>    except FileNotFoundError:
>>>        ...[B]...
>>>    try:
>>>        ...[A]...
>>>    finally:
>>>        f.close()
>>
>> What's the problem with spelling the above
>>
>> try: 
>>     f = open(...)
>> except FileNotFoundError:
>>     ...
>> with f:
>>     ...
>
> Nothing.

Well, in general, the "with" statement may require a special object that
must be used inside the "with" block. Thus, your enhancement might have
to be corrected:

   try:
       f = open(...)
   except FileNotFoundError:
       ...[B]...
   with f as ff:
       ...[A]... # only use ff here


Your version *might* be fine as it is mentioned specially:

   An example of a context manager that returns itself is a file object.
   File objects return themselves from __enter__() to allow open() to be
   used as the context expression in a with statement.

   <URL: https://docs.python.org/3/library/stdtypes.html#contextmanage
   r.__enter__>

I say "might" because the above statement is not mentioned in the
specification of open() or "file object".


Marko



More information about the Python-list mailing list