Search code examples
pythonpython-3.ximportglobal-variablesglobal

Python modify global variable


So, this is a bit tricky.

file1.py

a = None

def set_a():
    global a
    a = 10

file2.py

from file1 import a, set_a

set_a()
print(a)

output:

None

Why a's value didn't change? I know there are other ways to change the value of a, but why this doesn't work?


Solution

  • The big problem is where globals actually lives. Each script has its own globals. So the globals that is in set_a really points to file1's scope:

    import file1
    
    file1.set_a()
    a
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    NameError: name 'a' is not defined
    file1.a
    10
    

    This change does not persist to your calling script. So let's just avoid the global entirely.

    It would be much clearer for the function to just return the value, which you can name whatever you want in the calling script:

    # file1.py
    def set_a():
        return 10
    
    # file2.py
    from file1 import set_a
    
    # this doesn't have any reliance on a name existing
    # in any namespaces
    a = set_a()
    

    The general concensus on the issue is to avoid globals where possible, as they can make your code difficult to maintain.