All of the following is in one file:
def inner_foo(in_arg):
global x;
x += 99
return in_arg + 1
def outer_foo(in_arg):
global x;
x = 0
output = inner_foo(in_arg)
return output
result = outer_foo(5)
print("result == ", result)
print("x == ", x)
It works just fine when it is all in one file. Here is what gets printed:
result == 6
x == 99
However, if we try to split the program across multiple files, we run into problems.
# CONTENTS OF inner_foo.py
def inner_foo(in_arg):
global x;
x += 99
return in_arg + 1
Here is the other file:
# CONTENTS OF outer_foo.py
from inner_foo import inner_foo
def outer_foo(in_arg):
global x
x = 0
output = inner_foo(in_arg)
return output
result = outer_foo(5)
print("result == ", result)
print("x == ", x)
We get an error NameError: name 'x' is not defined
on the line x += 99
inside inner_foo.py
Changing the import statement to include x (from inner_foo import inner_foo, x
) gives us:
ImportError: cannot import name 'x'