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.
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?
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.
Activity
ngoldbaum commented on Apr 1, 2025
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?
kumaraditya303 commented on Apr 13, 2025
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.
lysnikolaou commented on Apr 28, 2025
If this isn't a real problem, should we remove the warnings from the docs? Or at least rephrase it?