Skip to content

Context manager support for contextvars.Context#99633

@rhansen

Description

@rhansen

Feature or enhancement

I would like to add __enter__ and __exit__ methods to contextvars.Context such that these two are mostly equivalent:

contextvars.copy_context().run(do_something_interesting)

and:

withcontextvars.copy_context(): do_something_interesting()

Pitch

This makes it possible to combine Context enter/exit with other context managers:

importcontextlibimportcontextvars@contextlib.contextmanagerdeffoo(): withcontextvars.copy_context(): set_some_context_vars() yield

My personal motivating interest is controlling ContextVar values in pytest fixtures. For example:

importcontextvarsimportpytestimportmodule_under_test@pytest.fixturedefclean_slate(): withcontextvars.copy_context(): module_under_test._internal_state_context_var.set(None) yielddeftest_foo(clean_slate): assertnotmodule_under_test.is_initialized()

Previous discussion

https://stackoverflow.com/q/59264158

Linked PRs

Metadata

Metadata

Assignees

No one assigned

    Labels

    stdlibStandard Library Python modules in the Lib/ directorytype-featureA feature request or enhancement

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions