Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Am I one of your patients? #4

Open
black-snow opened this issue Aug 23, 2024 · 0 comments
Open

Am I one of your patients? #4

black-snow opened this issue Aug 23, 2024 · 0 comments

Comments

@black-snow
Copy link

black-snow commented Aug 23, 2024

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant