user196574
user196574

Reputation: 113

Imported functions depending on parameters from main python file

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.

Upvotes: 0

Views: 280

Answers (1)

root
root

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

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) 

Upvotes: 1

Related Questions