A way to add typings to contextvars in Python

Viewed 924

Is there a way to type out the results when calling the get method on a ContextVar?

Something like this

from contextvars import ContextVar

my_var : ContextVar[MyType] = ContextVar('my_var', default=None)

So later I could have type hints(intellisense) with my IDE after calling the get method

current_val = my_var.get() # Now the IDE knows the type because of the generic

Does something like this exists or should I better create an issue in the python repo( or the mypy repo?)?

1 Answers

I have an alternative package to contextvars - I came back to developing it in the last couple of weeks - the main idea is to have a friendlier interface than "contetvars" get/set/copy_context/run semantics - and the first fully implemented class works like threading.local, as an arbitrary namespace.

I had not thought of type-hinting/guessing yet - but in seeing your question, it did work this way:

from extracontext import ContextLocal

class MyContext(ContextLocal):
    my_var: MyType
    other_var: OtherType


mycontext = MyContext()  # use this as the namespace:
mycontext.my_var = 20

mycontext._run(my_function) # the same as contextvars.Context.run -

# the instance can also be used in a context-manager block ("with" statement)
# or as a decorator to sync functions that need separate contexts.
# independent context values for new threads or async-tasks is automatic)

It will work naturally. The only point is that extracontext is not yet published (2021-03-09), you'd have to install from git with:

pip install -U git+https://github.com/jsbueno/extracontext.git@0.2b2

This version have a pure-Python implementation of asyncio-local context class which stores data in a running-frame closure, using f_locals as a mapping - I am working on a contextvars-backed class that will preserve roughly the same semantics.

https://github.com/jsbueno/extracontext

Related