I have a context var in in file a.py and I want to use it in b.py.
a.py:
import contextvars
cntx = contextvars.ContextVar("abcd")
b.py:
from .a import cntx
print(cntx.get())
Error:
Traceback (most recent call last):
File "/home/user/Desktop/b.py", line 1, in <module>
from .a import cntx
ImportError: attempted relative import with no known parent package
Isn't this how context variables supposed to work? I'm using python 3.9
The
ImportErrorthat you are getting is because of the invalid file name..ais a valid file name and would work if you had a file with filename being.a.pyThe reason you are getting the
LookupError: <ContextVar name='abcd' at 0x7f7d6209c5e0>is because you are trying toget()the context which hasn't been set yet.The get() method raises a LookupError if no context was set before.
Try with following -
a.py:
b.py:
When you run
b.py-Output: