Wang Honghui
Wang Honghui

Reputation: 92

Can not modify global variable in an asynchronous function (coroutine) in python

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)

And the result is: enter image description here

The jupyter notebook environment I am using is:

Upvotes: 0

Views: 1348

Answers (1)

Artyom Vancyan
Artyom Vancyan

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

Related Questions