43

What is a global statement? And how is it used? I have read Python's official definition;
however, it doesn't make a lot of sense to me.

Honest Abe
  • 8,430
  • 4
  • 49
  • 64
Capurnicus
  • 8,171
  • 5
  • 18
  • 11
  • 3
    just a remark, 2.4 is an old version of python, the actual reference for [python 2.X version is here](http://docs.python.org/2/reference/simple_stmts.html#global) – Cédric Julien Dec 14 '12 at 15:18
  • 2
    Python 3 comes with new statement `nonlocal` along with `global`, see it too. – Taha Jahangir Dec 14 '12 at 15:21
  • @TahaJahangir -- That's a good point. I've also added a little blurb on `nonlocal` in my answer because of your comment. Thanks! – mgilson Dec 14 '12 at 15:41

5 Answers5

74

Every "variable" in python is limited to a certain scope. The scope of a python "file" is the module-scope. Consider the following:

#file test.py
myvariable = 5  # myvariable has module-level scope

def func():
    x = 3       # x has "local" or function level scope.

Objects with local scope die as soon as the function exits and can never be retrieved (unless you return them), but within a function, you can access variables in the module level scope (or any containing scope):

myvariable = 5
def func():
    print(myvariable)  # prints 5

def func2():
    x = 3
    def func3():
        print(x)       # will print 3 because it picks it up from `func2`'s scope
    
    func3()

However, you can't use assignment on that reference and expect that it will be propagated to an outer scope:

myvariable = 5
def func():
    myvariable = 6     # creates a new "local" variable.  
                       # Doesn't affect the global version
    print(myvariable)  # prints 6

func()
print(myvariable)      # prints 5

Now, we're finally to global. The global keyword is the way that you tell python that a particular variable in your function is defined at the global (module-level) scope.

myvariable = 5
def func():
    global myvariable
    myvariable = 6    # changes `myvariable` at the global scope
    print(myvariable) # prints 6

func()
print(myvariable)  # prints 6 now because we were able 
                   # to modify the reference in the function

In other words, you can change the value of myvariable in the module-scope from within func if you use the global keyword.


As an aside, scopes can be nested arbitrarily deeply:

def func1():
    x = 3
    def func2():
        print("x=",x,"func2")
        y = 4
        def func3():
            nonlocal x  # try it with nonlocal commented out as well.  See the difference.
            print("x=",x,"func3")
            print("y=",y,"func3")
            z = 5
            print("z=",z,"func3")
            x = 10

        func3()

    func2()
    print("x=",x,"func1")

func1()

Now in this case, none of the variables are declared at the global scope, and in python2, there is no (easy/clean) way to change the value of x in the scope of func1 from within func3. That's why the nonlocal keyword was introduced in python3.x . nonlocal is an extension of global that allows you to modify a variable that you picked up from another scope in whatever scope it was pulled from.

Dan Swain
  • 2,910
  • 1
  • 16
  • 36
mgilson
  • 300,191
  • 65
  • 633
  • 696
  • +1 for a thorough explanation. However, you may want to show the results of the print statements. – Steven Rumbalski Dec 14 '12 at 15:25
  • Tested this myself after reading your answer and my understanding has vastly improved on this subject. Thank you very much! – Capurnicus Dec 14 '12 at 15:36
  • 3
    @user1901780 -- It's also worth pointing out that **most** of the time, sharing data via `global` is considered to be a bad idea as it makes it more difficult to encapsulate your logic. The better way to have data persist between function calls is to use `class`es which is something you'll probably want to learn if you stick with `python` long enough :) – mgilson Dec 14 '12 at 15:47
4

mgilson did a good job but I'd like to add some more.

list1 = [1]
list2 = [1]

def main():
    list1.append(3)
    #list1 = [9]
    list2 = [222]

    print list1, list2


print "before main():", list1, list2
>>> [1] [1]
main()
>>> [1,3] [222]
print list1, list2    
>>> [1, 3] [1]

Inside a function, Python assumes every variable as local variable unless you declare it as global, or you are accessing a global variable.

list1.append(2) 

was possible because you are accessing the 'list1' and lists are mutable.

list2 = [222]

was possible because you are initializing a local variable.

However if you uncomment #list1 = [9], you will get

UnboundLocalError: local variable 'list1' referenced before assignment

It means you are trying to initialize a new local variable 'list1' but it was already referenced before, and you are out of the scope to reassign it.

To enter the scope, declare 'list1' as global.

I strongly recommend you to read this even though there is a typo in the end.

YOUNG
  • 515
  • 3
  • 13
1
a = 1

def f():
    a = 2 # doesn't affect global a, this new definition hides it in local scope

a = 1

def f():
    global a
    a = 2 # affects global a
StoryTeller - Unslander Monica
  • 165,132
  • 21
  • 377
  • 458
0

Basically it tells the interpreter that the variable its given should be modified or assigned at the global level, rather than the default local level.

Jakob Bowyer
  • 33,878
  • 8
  • 76
  • 91
0

You can use a global variable in other functions by declaring it as global in each function that modifies it

Python wants to make sure that you really know that's what you're playing with by explicitly requiring the global keyword.

See this answer

Community
  • 1
  • 1
vivek
  • 4,951
  • 4
  • 25
  • 33