Skip to content

Improve ContextVar in closures documentation #131837

Description

@lysnikolaou

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.

Linked PRs

Activity

  1. ngoldbaum commented on Apr 1, 2025

    @ngoldbaum
    Contributor

    I just found a spot in a library where it would be nice to make a context variable an attribute of a class. @kumaraditya303 can you explain a little more why you think the note in the ContextVar docs is wrong?

  2. kumaraditya303 commented on Apr 13, 2025

    @kumaraditya303
    Contributor

    I think what "properly garbage collected" means here is that it there is a refcycle between context and contextvar so if the contextvar is created as class attribute then it will extend its lifetime whereas creating it on module level leads to it being destroyed earlier when modules are finalized.
    I don't think this is real problem though because in the end gc will break the cycle anyways when the "class" will be deallocated later in runtime finalization.

  3. lysnikolaou commented on Apr 28, 2025

    @lysnikolaou
    MemberAuthor

    I don't think this is real problem though

    If this isn't a real problem, should we remove the warnings from the docs? Or at least rephrase it?

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

    docsDocumentation in the Doc dir

    Projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions