Reputation: 113
I am a new user to Python, and I am mostly unfamiliar with imports. I've run into an issue where a function is defined in an imported python file, but its definition includes objects that were not defined in the imported file. Here is a minimum working example:
def printL():
print(L)
return()
import test1 as T1
L=10
T1.printL()
yields the error
Traceback (most recent call last):
File "filepath/test2.py", line 3, in <module>
T1.printL()
File "filepath/test1.py", line 2, in printL
print(L)
NameError: name 'L' is not defined
The example above is just illustrative. I was a little surprised, since the following function works just fine:
def printL():
print(L)
return()
L=10
printL()
Why doesn't test2.py
above work? It seems to be ignoring that I've assigned L=10
.
Is there something I can do in test2.py
to ensure that when it runs it will use the value L=10
in T1.printL()
? I'm imagining making some sort of copy of the function printL()
or making variables global.
Upvotes: 0
Views: 280
Reputation: 26
The problem is that: L variable is defined in the file test2.py, so visible only in this file and the L variable in the body of printL function in test1.py is a local variable, visible only in this file too.
Try this instead
def printL(L):
print(L)
return()
import test1 as T1
L=10
T1.printL(L)
L = 10
print(L)
Upvotes: 1