pythonpython-3.xglobal

in Python why do I get "name 'a' is not defined" even though I have defined it as global?


Here is example code:

async def main():

    a = 10
    async def test():
        global a
        a +=2
        print(a)
    
    await test()
    
asyncio.run(main())

and the resulting error: a +=2 ^ NameError: name 'a' is not defined


Solution

  • Because in this example a isn't a global variable. Its in the local space of the main function. For it to be global a needs to be completely outside everything

    Also on another note, adding to global variables concurrently without any form of locking on the variable is a bad idea as it can lead to unexpected results