[Python-ideas] Letting context managers react to yields inside their scope

Nick Coghlan ncoghlan at gmail.com
Thu Apr 30 02:53:19 CEST 2015


On 30 April 2015 at 07:01, Yury Selivanov <yselivanov.ml at gmail.com> wrote:
> I think that the right approach here would be to have a
> standard protocol; something similar to how we defined
> WSGI -- it doesn't require any changes in the interpreter,
> it is a protocol.

+1 - I think we have reasonably good precedent for this in the form of
atexit and there's also a proposal for an "atfork" manager:
https://bugs.python.org/issue16500

Decimal contexts and (to a much lesser degree) fpectl are also
interesting use cases, as is the event loop policy management in
asyncio.

One of the more interesting aspects of a context is its scope:

* Can the same context be safely accessed from multiple threads
concurrently? At different points in time?
* Is there a "default context" which applies if no other context has
been explicitly activated?

By defining a global metacontext, it becomes feasible to sensibly
manage things like the active asyncio event loop policy, the decimal
context, etc, in ways that multiple frameworks can interoperate with.
It's also potentially something that the logging module, pdb, and
other tools could integrate with, by being able to better report the
active context when requested.

https://docs.python.org/3/library/contextlib.html#contextlib.ExitStack
is also an interest data point, as I can easily envision a variant of
that API model that remembers what contexts *were* on the stack (this
becoming a "ContextStack", rather than an "ExitStack"), making it
easier to switch *between* stacks, rather than throwing them away when
you're done.

Cheers,
Nick.

-- 
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia


More information about the Python-ideas mailing list