Global variable and import

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

def init_foo():
    global foo 

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

import test1


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 while it is run? Also if you can provide a workaround for that problem?


2 answers

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

    why use global though? Just return it

    def init_foo():
        foo = 10
        return foo

    foo = test1.init_foo()

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

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