2

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?

Jack Feng
  • 895
  • 2
  • 9
  • 24
  • 2
    `set_a` does not _call_ function `set_a` – zvone Jan 13 '20 at 18:52
  • 1
    Even if what you are trying to do works, I'd suggest finding another way of solving the issue, you will probably run into [Cyclical dependencies](https://stackoverflow.com/questions/3400525/global-variable-from-a-different-file-python) problems – Manuel Jan 13 '20 at 18:55
  • @zvone, my bad, I changed it to set_a. It was a typo. The problem was not because of this. – Jack Feng Jan 13 '20 at 19:10

1 Answers1

3

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.

C.Nivs
  • 12,353
  • 2
  • 19
  • 44
  • found the answer. https://stackoverflow.com/questions/13403357/python-global-variables-dont-seem-to-work-across-modules – Jack Feng Jan 13 '20 at 19:17