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:
test1.py
def printL():
print(L)
return()
test2.py
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:
test3.py
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.
printLneeds the value ofL, then you need to pass it as a parameter. Globals in Python are only global to a single file (which is why test2 doesn't work), and the best practice is to avoid them whenever possible.