python / python/cpython

Context manager support for `contextvars.Context`

Open
#99,633 27 comments 12 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

stdlib type-feature
Dominant language
Python
Stars
77.2k
Forks
36k
PR merge metrics
PR metrics pending

Description

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:

with contextvars.copy_context():
    do_something_interesting()

Pitch

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

import contextlib
import contextvars

@contextlib.contextmanager
def foo():
    with contextvars.copy_context():
        set_some_context_vars()
        yield

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

import contextvars
import pytest
import module_under_test

@pytest.fixture
def clean_slate():
    with contextvars.copy_context():
        module_under_test._internal_state_context_var.set(None)
        yield

def test_foo(clean_slate):
    assert not module_under_test.is_initialized()

Previous discussion

https://stackoverflow.com/q/59264158

Linked PRs
  • gh-124773
  • gh-124776
  • gh-99634

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by reading the contextvars.Context documentation and the issue's equivalence examples, then review linked PRs gh-124773, gh-124776, and gh-99634 before starting. Done means Context supports the requested context-manager usage and the behavior matches the existing run() example, including composition with other context managers.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
backend
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Clearly specified
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.