python / python/cpython

Improve ContextVar in closures documentation

Open
#131,837 3 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

docs
Dominant language
Python
Stars
77.2k
Forks
35.9k
PR merge metrics
PR metrics pending

Description

Documentation

In the [documentation for contextvars.ContextVar], there is the following warning:

Important: Context Variables should be created at the top module level and never in closures. Context objects hold strong references to context variables which prevents context variables from being properly garbage collected.

@kumaraditya303 and I talked about it and he claimed that this is not the case any more (that was at least my understanding) and ContextVars can be defined as class/instance attributes for example. If that's the case, we should probably update the docs. Otherwise, it might make sense to emphasize on it even more, now that ContextVars will be even more widely used due to free-threading.

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 with the documentation for contextvars.ContextVar and verify whether the warning about closures and garbage collection is still accurate, including class and instance attributes. Done when the documentation clearly reflects the confirmed behavior and guidance.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
documentation
Issue type
Documentation
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.