Reputation: 92
I run this code in jupyter notebook(python 3.6.8). I expect the code to print 2 as the result, somehow it still prints 1. I want to know why.
import asyncio
x = 1
async def func():
global x
x = 2
print(x)
await func()
print(x)
The jupyter notebook environment I am using is:
Upvotes: 0
Views: 1348
Reputation: 5390
If you want to change a global variable in IPython
coroutine you have to acquire the asyncio.Lock
.
import asyncio
x = 1
async def func():
global x
lock = asyncio.Lock()
await lock.acquire()
x = 2
lock.release()
await func()
print(x) # 2
Upvotes: 0