0

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!

jim jarnac
  • 4,804
  • 11
  • 51
  • 88
  • "Global" means "module-scoped", and specifically, scoped to the module where the code is defined. There exists no such thing in Python as a scope that spans multiple modules, or a means to refer to the calling module's variables (which is for the better -- if the language *did* support a thing, you'd never be able to use a 3rd-party module without first checking if its global names conflicted with yours). – Charles Duffy Feb 13 '18 at 00:49
  • "Also if you can provide a workaround for that problem?" Don't design your program to depend on shared global state across modules... Even global state within modules is iffy.. – juanpa.arrivillaga Feb 13 '18 at 01:27

2 Answers2

0

why use global though? Just return it

test1.py

def init_foo():
    foo = 10
    return foo

test2.py

foo = test1.init_foo()
print(foo)
Moller Rodrigues
  • 780
  • 5
  • 16
  • Ok thx for your answer, which is the workaround. But why is the global not working? – jim jarnac Feb 13 '18 at 00:48
  • @jimbasquiat `foo` is a global variable just at the file-level in the file `test1.py`. So, you need to do `test1.foo` to access it in a different file `test2.py`. – Vikram Hosakote Feb 13 '18 at 00:55
0

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

Vikram Hosakote
  • 3,528
  • 12
  • 23