[Python-ideas] 回复:Python-ideas Digest, Vol 146, Issue 13

Nathaniel Smith njs at pobox.com
Sun Jan 6 00:23:40 EST 2019


On Sat, Jan 5, 2019 at 9:13 PM Moon丶sun <uamr567 at sina.com> wrote:
>
> Thanks for your reply.
> But the answer is not I except, I will show you some examples to explain what result I except:
>
> @contextmanager
> def cm():
>     print('open file')
>     yield
>     print('close file')
> with cm():
>     1/0
>
> If I use a contextmanager ,I except it can help me to close the file anytime,even raise an error,
> but if I define a function with @contextmanager like the example which I have showed for you,
> it will never print('close file')
>
> I can only modify it like this:
> @contextmanager
> def cm():
>     try:
>         print('open file')
>         yield
>     except Exception as e:
>         print('Error',e)
>     finally:
>         print('close file')
>
> It is not friendly for us to use it, so I modify the contextlib to fix it,you can catch it from the e-mail attachment.
> It's in the line 79 and line 97

This is intentional, and can't be changed without breaking lots of code.

With your version, there's no way for the context manager to catch or
modify the exception, which is a common use case. For example, here's
a context manager I wrote recently:

@contextmanager
def catch_and_log(exctype):
    try:
        yield
    except exctype:
        log.exception(...)

This can't be done using your version.

Of course you can have your own version of @contextmanager that works
however you prefer.

-n

-- 
Nathaniel J. Smith -- https://vorpus.org


More information about the Python-ideas mailing list