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.