[Python-Dev] On suppress()'s trail blazing (was Re: cpython: Rename contextlib.ignored() to contextlib.ignore())
Barry Warsaw
barry at python.org
Thu Oct 17 20:48:59 CEST 2013
On Oct 17, 2013, at 08:40 PM, Xavier Morel wrote:
>I think there's already a significant split between context managers
>which handle the lifecycle of a local resource (file, transaction) and
>those which purport to locally alter global-ish state (cwd,
>decimal.localcontext, logging.captureWarnings, redirect_stdout).
>
>And the latter worries me (much more than the very localized behavior of
>suppress) because I don't see any way to implement them safely and
>correctly when mixing it with coroutines in today's Python (some of them
>aren't even thread-safe), all of that while I expect coroutines will see
>significantly more use in the very near future with yield from and
>tulip's promotion of coroutine-style async.
Although slightly orthogonal to my previous distinction, this is a great
point. Anything affecting global state will have this problem of course.
It's definitely something to keep thinking about.
>> Just look at the implementation to see this shift in perspective. It
>> doesn't use try/finally, it uses try/except.
>
>Transaction CMs will also use try/except:
>
> @contextmanager
> def transaction():
> resource = open_tnx()
> try:
> yield resource
> resource.commit()
> except:
> resource.rollback()
> raise
True. I'm sure lots of us have code almost exactly like this. ;) For me, it's
closer to the original intent though because the bare-except combined with the
re-raising of the exception feels kind of like a finally. In both exit paths,
the resource is being released, it's just that you have to know which
"release" operation to perform.
Cheers,
-Barry
More information about the Python-Dev
mailing list