Global variable with imports

Joel picture Joel · Jan 16, 2011 · Viewed 22.1k times · Source

first.py

myGlobal = "hello"

def changeGlobal():
   myGlobal="bye"

second.py

from first import *

changeGlobal()
print myGlobal

The output I get is

hello

although I thought it should be

bye

Why doesn't the global variable myGlobal changes after the call to the changeGlobal() function?

Answer

TryPyPy picture TryPyPy · Jan 16, 2011

Try:

def changeGlobal():
    global myGlobal
    myGlobal = "bye"

Actually, that doesn't work either. When you import *, you create a new local module global myGlobal that is immune to the change you intend (as long as you're not mutating the variable, see below). You can use this instead:

import nice

nice.changeGlobal()
print nice.myGlobal

Or:

myGlobal = "hello"

def changeGlobal():
   global myGlobal
   myGlobal="bye"

changeGlobal()

However, if your global is a mutable container, you're now holding a reference to a mutable and are able to see changes done to it:

myGlobal = ["hello"]

def changeGlobal():
    myGlobal[0] = "bye"