1

I am trying to use a global variable across modules by importing the variable and modifying it locally within a function. The code and the output is below. The last output is not what I expected, I thought it should be 15 since it has been already modified in global scope by func3. Can anybody please explain why the last output is still 10.

Thank you!

test2.py

myGlobal = 5
def func3():
    global myGlobal
    myGlobal = 15
    print "from 3: ", myGlobal

test1.py

from test2 import myGlobal, func3

def func1():
    global myGlobal
    myGlobal = 10

def func2():
    print "from 2: ", myGlobal

print "init: ", myGlobal
func1()
func2()
func3()
func2()

The outputs:

init:  5
from 2:  10
from 3:  15
from 2:  10
Abhi
  • 1,167
  • 2
  • 14
  • 21
  • `func3` uses itself `myGlobal` not imported `myGlobal` in `test1.py` – Farhadix Nov 15 '13 at 19:24
  • 5
    There are no true globals in Python; the module has its own "global" namespace. You can explicitly modify `test2.myGlobal`, but the `global` keyword won't let you rebind names in another module. – Wooble Nov 15 '13 at 19:25
  • 2
    Please, don't write code like that, it is unnecessary, makes the code harder to reason about, and it is harder to test. – Augusto Hack Nov 15 '13 at 19:26

1 Answers1

1

As stated in the comments, global in Python means module level.

So doing:

a = 1

Has the exact same effect on a as:

def f():
    global a
    a = 1
f()

And in both cases the variable is not shared across modules.

If you want to share a variable across modules, check this.

Community
  • 1
  • 1
Ciro Santilli OurBigBook.com
  • 347,512
  • 102
  • 1,199
  • 985