pythonpython-3.xerror-handlingimporterrorpython-contextvars

How can I use context vars in other file in python 3.7 or above?


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


Solution

  • The ImportError that you are getting is because of the invalid file name. .a is a valid file name and would work if you had a file with filename being .a.py

    The reason you are getting the LookupError: <ContextVar name='abcd' at 0x7f7d6209c5e0> is because you are trying to get() 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:

    import contextvars
    
    cntx = contextvars.ContextVar("abcd")
    cntx.set("example")
    

    b.py:

    from a import cntx
    print(cntx.get())
    

    When you run b.py -

    Output:

    example