Global variable and import

Let's consider a file called test1.py and containing the following code:

def init_foo():
    global foo 
    foo=10

Let's consider another file called test2.py and containing the following:

import test1

test1.init_foo()
print(foo)

Provided that test1 is on the pythonpath (and gets imported correctly) I will now receive the following error message:

NameError: name 'foo' is not defined

Anyone can explain to me why the variable foo is not declared as a global in the scope of test2.py while it is run? Also if you can provide a workaround for that problem?

Thx!

2 answers

  • answered 2018-02-13 00:28 Moller Rodrigues

    why use global though? Just return it

    test1.py

    def init_foo():
        foo = 10
        return foo
    

    test2.py

    foo = test1.init_foo()
    print(foo)
    

  • answered 2018-02-13 00:28 Vikram Hosakote

    In test2.py, do print(test1.foo) instead of print(foo) and it will work.