0

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

2
  • 2
    why cant you just pass it as argument? why use global variables ? Commented May 8, 2020 at 12:07
  • func1 is in a module and you have to set the attribute of the module (DefTest.x = 1) Commented May 8, 2020 at 12:55

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

in test.py, use the fully qualified name: deftest.x = 1

Comments

0

You should pass the variable name x with the Package DefTest in the test.py file

DefTest.x = 1
DefTest.func1()

Comments

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.