Suppose we save the following into a Python file called test.py
:
x = 14
def print_x():
print x
def increment_x():
x += 1
and then run the following from an interactive Python shell in the same directory:
from test import print_x, increment_x
print_x()
increment_x()
print x
Why does the third call produce an error? Doesn't x
need to be defined for the first two to work?
The functions do not throw an error because they still live in the module test, and they still see x in the module test. When you import a reference to a function elsewhere it dose not really move, or become disconnected from its original context. If it did there wouldn't be much use for modules.