I've read the PEP and understand what's implemented. However there is pretty 
limited discussion about what the design constraints were and what 
intended/recommended usage would look like. I'll answer my own question:

1. If all we wanted was a version of TLS that worked in an analogous way 
extending (synchronous code, threads) to (async code, tasks) then you don't 
need anything fancy, a simple dictionary backing the "context" will do. This is 
all that you need to solve the "decimal formatting" problem, for instance.

2. However, the scope of PEP 567 was increased to something greater. It was 
decided that we want tasks/threads to be able to inherit an existing context. 
This is a unique feature with no analog in TLS. I believe a motivating use case 
was for a request/response server that may spawn worker tasks off the main task 
and want to store request context information in contextvars.

3. Additionally, to continue to have the "decimal formatting" solution work 
correctly it's necessary that no two tasks/threads are running on the same 
context. This means "inherting" should mean "running on a copy of".

These constraints strongly suggest an interface of:

contextvars.get_context() -> Context
Context.run_in_copy(func) -> Context
Context.async_run_in_copy(coro) -> Context
*** NoContext.run method, no copy methods needed either ***

So what was the motivation behind having a copy_context() and a non-copying 
Context.run method? It seems to break the third design constraint allowing you 
to have multiple threads try and run on the same Context.

Nonetheless, "asyncio.run_in_context()" is a direct analog of "Context.run" and 
should be a clear add to the API from a symmetry point of view. We are already 
beyond the point where constraint three is being strictly enforced. I'm not 
sure what argument against this API wouldn't apply to "Context.run()" as well.

If it's still a -1 on "asyncio.run_in_context()" what about 
"asyncio.run_in_context_copy(context, coro) -> Context" that copies the passed 
context and runs the coroutine in the task using that context? If we go this 
route maybe we would plan on deprecating Context.run and replacing it with a 
Context.run_in_copy method?
_______________________________________________
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/4SYYJEVIV3ZUSVBZIL34EZTIEMBRV533/
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to