Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading