pythonpython-contextvars

What happens if I don't reset Python's ContextVars?


Is this a memory leak in Python?

import contextvars

contextvar = contextvars.ContextVar('example')

while True:
   string = 'hello world'
   token = contextvar.set(string)

Is a contextvar a stack that keeps on growing the more you push to it?

What if I never call contextvar.reset(token)?

Or is everything handled with reference counting?


Solution

  • The "token" object object contains the recover-value as a plain attribute of itself (.old_value). Regardless of internal representations, the old values will live for as long as you keep one reference to the token around.

    Now, if the ContextVar object would stack references to its values whenever a new one is "set" you could have something to worry - it does not seem to be the case: the old value is kept in the token itself (and by creating a list of tokens I could use an of them at will to reset the value of when the token was created, regardless of order - so, all the token does is to ensure it can only be used with the ContextVar that created it)

    (in time: the experiment in the answer by @mkrieger1 was here first and provided me important information to be able to do my own tests and assert that the token value is preserved within the token, not within the context)