DefTest.py
def fun1():
print x
test.py
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
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.
func1is in a module and you have to set the attribute of the module (DefTest.x = 1)