0

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.

2
  • 2
    No. If printL needs the value of L, 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. Commented Jul 29, 2022 at 3:04
  • @TimRoberts Thanks, if you write that as an answer, I'll accept it. Commented Jul 29, 2022 at 3:08

1 Answer 1

1

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

test1.py

def printL(L):
    print(L)
    return()

test2.py

import test1 as T1
L=10
T1.printL(L)     

Here is a best practice and more concise code:

test.py

L = 10
print(L) 
Sign up to request clarification or add additional context in comments.

1 Comment

I believe you wanted T1.print(L).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.