[Python-ideas] New PEP 550: Execution Context
Barry Warsaw
barry at python.org
Mon Aug 14 14:09:41 EDT 2017
Yury Selivanov wrote:
> This is a new PEP to implement Execution Contexts in Python.
It dawns on me that I might be able to use ECs to do a better job of
implementing flufl.i18n's translation contexts. I think this is another
example of what the PEP's abstract describes as "Context managers like
decimal contexts, numpy.errstate, and warnings.catch_warnings;"
The _ object maintains a stack of the language codes being used, and you
can push a new code onto the stack (typically using `with` so they get
automatically popped when exiting). The use case for this is
translating say a notification to multiple recipients in the same
request, one who speaks French, one who speaks German, and another that
speaks English.
The problem is that _ is usually a global in a typical application, so
in an async environment, if one request is translating to 'fr', another
might be translating to 'de', or even a deferred context (e.g. because
you want to mark a string but not translate it until some later use).
While I haven't used it in an async environment yet, the current
approach probably doesn't work very well, or at all. I'd probably start
by recommending a separate _ object in each thread, but that's less
convenient to use in practice. It seems like it would be better to
either attach an _ object to each EC, or to implement the stack of codes
in the EC and let the global _ access that stack.
It feels a lot like `let` in lisp, but without the implicit addition of
the contextual keys into the local namespace. E.g. in a PEP 550 world,
you'd have to explicitly retrieve the key/values from the EC rather than
have them magically appear in the local namespace, the former of course
being the Pythonic way to do it.
Cheers,
-Barry
More information about the Python-ideas
mailing list