I just stumbled over an issue with contextvars and async generators in my code. That led me to https://peps.python.org/pep-0568/ and further research brought me here.
I'm not 100% sure this is the actual problem, though - it's about 1 am now and after reading a lot my brain is a bit fried.
Let me describe my issue in code:
from unittest.mock import Mock
import contextvars
async def test_():
m = Mock()
cv = contextvars.ContextVar("cv", default={})
async def dummy_async_method(i: int):
# wrapped.set_mdc({f"coro{i}": f"coro{i}"})
cv.set({f"coro{i}": f"coro{i}"})
m.info(cv.get())
yield f"c{i}.1"
# cv({f"coro{i}": f"coro{i}"}) # by setting the var again the test passes
m.info(cv.get())
yield f"c{i}.2"
gen1 = dummy_async_method(1)
gen2 = dummy_async_method(2)
# assert expected execution order
assert await anext(gen1) == "c1.1"
assert await anext(gen2) == "c2.1"
assert await anext(gen1) == "c1.2"
assert await anext(gen2) == "c2.2"
# assert logger invocations with correct context
assert m.info.call_args_list[0].args[0] == {"coro1": "coro1"}
assert m.info.call_args_list[1].args[0] == {"coro2": "coro2"}
assert m.info.call_args_list[2].args[0] == {"coro1": "coro1"} # <-- fails here, is coro2: coro2
assert m.info.call_args_list[3].args[0] == {"coro2": "coro2"} # this, too, is coro2: coro2
I am like .93 confident I'm in the right place and I'll give extracontent a shot somewhere next week. But perhaps someone's faster.
Was there ever a follow-up to PEP 568? I can't find any plans on fixing this issue.
P. S.:
There's a print in PyContextLocal's constructor - is that intended? ;)
Also, the indentation in the first example here is off. I may file a PR once I caught some sleep.
I just stumbled over an issue with
contextvarsand async generators in my code. That led me to https://peps.python.org/pep-0568/ and further research brought me here.I'm not 100% sure this is the actual problem, though - it's about 1 am now and after reading a lot my brain is a bit fried.
Let me describe my issue in code:
I am like .93 confident I'm in the right place and I'll give
extracontenta shot somewhere next week. But perhaps someone's faster.Was there ever a follow-up to PEP 568? I can't find any plans on fixing this issue.
P. S.:
There's a
printinPyContextLocal's constructor - is that intended? ;)Also, the indentation in the first example here is off. I may file a PR once I caught some sleep.