Skip to content

Am I one of your patients? #4

Description

@black-snow

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.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions