Reputation: 3
def fun1():
print x
import DefTest
x = 1
DefTest.fun()
Why do I get "NameError: global name 'x' is not defined" when executing test.py? How do I properly set this up so I can grab this function
Upvotes: 0
Views: 88
Reputation: 989
You should pass the variable name x with the Package DefTest in the test.py file
DefTest.x = 1
DefTest.func1()
Upvotes: 0
Reputation: 531235
Each module has its own global scope. fun
uses DefTest.x
, not test.x
.
>>> import DefTest
>>> DefTest.x = 5
>>> DefTest.fun()
5
You might think the following would also work
from DefTest import x
x = 5
DefTest.fun()
but it doesn't, because from DefTest import x
creates a new global variable in the module test
which is initialized using the value of DefTest.x
, rather than creating an "alias" to DefTest.x
.
Upvotes: 1