importing function giving scoping error

61 Views Asked by At

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?

2

There are 2 best solutions below

0
On

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.

0
On

The reason why you get a Scope error message is because x is only global in test.py and when you do:

from test import print_x, increment_x

You are not actually importing x to the global scope of the second script.

So, if you want to make x global as well in the second script, do:

from test import *

Try to use the DEBUGGER utility within IDLE to see when x is GLOBAL and when is not