Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ContextVar not preserved when cell contains await #749

Open
mvolfik opened this issue Aug 18, 2021 · 3 comments
Open

ContextVar not preserved when cell contains await #749

mvolfik opened this issue Aug 18, 2021 · 3 comments

Comments

@mvolfik
Copy link

mvolfik commented Aug 18, 2021

See https://gist.github.com/mvolfik/2582939ec00120a04503507214c24105

import contextvars, asyncio
VAR = contextvars.ContextVar("VAR", default="default")

async def produce_result(x):
    return x

async def read_var():
    print("Var:", VAR.get())


# The following is broken

# In[3]:
result = await produce_result("bug fixed yayy")
VAR.set(result)

# In[4]:
await read_var()
# Var: default


# The following works

# In[5]:
result = await produce_result("this worked before")

# In[6]:
VAR.set(result)

# In[7]:
await read_var()
# Var: this worked before

In the working case, await result is stored in a variable, and VAR is set from cell which is fully synchronous (idk ipython internals, but that's what I guess makes the difference). What breaks is setting var from the same cell where we call and await the async function.

I'm using ipykernel==6.2.0. Neither of these cases worked (both outputted 'default') with ipykernel==5.5.0.

Related to ipython issue ipython/ipython#11565, which was fixed by #632

@tbenthompson
Copy link

I ran into this same issue today with ipykernel==6.20.2.

@RRRajput
Copy link

This is still an issue

@alexbarcelo
Copy link

I have ran into this and see no workaround nor any way to solve it.

Has somebody found any alternative for allowing my code to work? I am using code as an external library and it is broken because of this ContextVar variable being lost between cells.

Also, what does anybody know the technical reason behind this limitation? I was trying to debug and pinpoint the origin but I don't know a lot of internals, I assume that ipykernel is creating a task/copying context when the cell contains an await and thus it is breaking the expected code flow but that is a wild assumption that I have not confirmed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants