[Python] Python doesn't recognize all global variables [closed]

Discussão em 'Python' iniciado por Stack, Setembro 25, 2024.

  1. Stack

    Stack Membro Participativo

    This has been asked before but the examples do not match this simple use case.

    Module One.py

    varname = 'var'
    var = 0


    Module Two.py

    from One import *

    def checkname():
    if (varname == 'not var'):
    print ('not var')
    print (var)


    When I run this, I get the error on line print (var)

    UnboundLocalError: cannot access local variable 'var' where it is not associated with a value

    So the global name varname is recognized and used, but the global name var is not used and instead seems to thought of as a local variable.

    If I do print(globals()) I can see both varname and var shown as global variables.

    If module Two is modified to

    from One import *

    def checkname():
    global var

    if (varname == 'not var'):
    print ('not var')
    print (var)


    Then this works. But why did I not have to really make it global varname, var

    Why did it allow varname without declaring it global while it didn't allow the use of var?

    Continue reading...

Compartilhe esta Página