I have two files:
lib.py
global var
def test():
var = "Hello!"
return
test.py
from lib import *
test()
print(var)
But despite having them in the same folder, when I run test.py, I get the following error:
Traceback (most recent call last):
File "C:\Test\test.py", line 5, in <module>
print(var)
NameError: name 'var' is not defined
How can I access this variable in a function in another file?
You need to declare the variable as global in the scope which it is used, which in this case is the function test()
:
def test():
global var
var = "Hello!"
Note that the final return
is not necessary, since it is implicit at the end of a function. Also, var
is declared in the global scope of the module, so it won't be imported automatically by from lib import *
since it's created after the module has been imported.
Returning var
from the function is probably a better solution to use across modules:
def test():
var = "Hello!"
return var
var = test()
print(var) # Hello!
I recommend the following:
lib.py
def test():
return "Hello!"
test.py
from lib import *
var = test()
print(var)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.