Skip to content

gh-131837: Clarify context variable lifetime in closures - #159849

Open
limadog9 wants to merge 1 commit into
python:mainfrom
limadog9:gh-131837-contextvar-lifetime-docs
Open

limadog9 wants to merge 1 commit into
python:mainfrom
limadog9:gh-131837-contextvar-lifetime-docs

Conversation

@limadog9

@limadog9 limadog9 commented Oct 20, 2026 •

Copy link
Copy Markdown
Contributor

Explain why creating context variables in closures can extend their lifetimes: a reachable Context holds strong references to variables with values set in it. Repeated creation and binding in a long-lived context can accumulate variables.

Keep the recommendation to create variables at module level while describing the actual retention condition instead of saying they cannot be properly garbage collected.

Fixes #131837.

Validation:

  • Used a weak-referenceable default value to confirm retention by a reachable context, collection after discarding the context, and collection after resetting the variable to its unset state.
  • Full HTML documentation build with warnings treated as errors.
  • Sphinx lint and patchcheck.

@read-the-docs-community

Copy link
Copy Markdown

Documentation build overview

📚 cpython-previews | 🛠️ Build #35258704 | 📁 Comparing 20a4450 against main (6044c62)

  🔍 Preview build  

1 file changed
± library/contextvars.html

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

Labels

awaiting review docs Documentation in the Doc dir skip news

Projects

Status: Todo

Development

Successfully merging this pull request may close these issues.

Improve ContextVar in closures documentation

1 participant