Scott Bodien
Scott Bodien

Reputation: 3

Python - Global variable not passing through to function

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

Upvotes: 0

Views: 88

Answers (3)

Dejene T.
Dejene T.

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

chepner
chepner

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

Demi-Lune
Demi-Lune

Reputation: 1977

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

Upvotes: 0

Related Questions