Search code examples
pythonglobal-variables

asyncio : very strange handling of global variables within tasks


if this function is run as a task in asyncio:

async def test():
    x = "strange"
    while True:
        def myfunc():
            global x
            x = "expected"
        myfunc()
        print("This is " + x)
        await asyncio.sleep(1)


loop.create_task(test())
loop.run_forever()

I would expect "This is expected" , same outcome as any normal python app... but instead.. it prints "This is strange" ... why ?


Solution

  • The question is not related to asyncio.

    global x links x variable to module-level object, not to test function.

    Use nonlocal x instead to make the code work as expected.