Coder Perfect

Use of “global” keyword in Python


What I understand from reading the documentation is that Python has a separate namespace for functions, and if I want to use a global variable in that function, I need to use global.

I’m running Python 2.7 and ran this little test.

>>> sub = ['0', '0', '0', '0']
>>> def getJoin():
...     return '.'.join(sub)
>>> getJoin()

Even without global, it appears that everything are running smoothly. Without any difficulty, I was able to access global variables.

Is there anything I’m overlooking? The following is also taken from the Python documentation:

While formal parameters and class definition make sense to me, I’m stumped by the loop control target and function definition restrictions.

Asked by nik

Solution #1

The keyword global is only helpful in a local context to update or create global variables, while generating global variables is rarely a suitable option.

def bob():
    me = "locally defined"    # Defined only in local context

print(me)     # Asking for a global variable

As a result of the preceding, you will be able to:

locally defined
Traceback (most recent call last):
  File "", line 9, in <module>
NameError: name 'me' is not defined

The variable will become available “outside” the scope of the function if you use the global statement, essentially making it a global variable.

def bob():
    global me
    me = "locally defined"   # Defined locally but declared as global

print(me)     # Asking for a global variable

As a result of the code above, you will receive:

locally defined
locally defined

You could also use global to define functions, classes, or other objects in a local environment due to the nature of Python. Although I would advise against it because if something goes wrong or needs debugging, it can be a nightmare.

Answered by unode

Solution #2

While you can access global variables without using the global keyword, you must use the global keyword to edit them. Consider the following scenario:

foo = 1
def test():
    foo = 2 # new local foo

def blub():
    global foo
    foo = 3 # changes the value of the global foo

You’re simply accessing the list sub in your scenario.

Answered by Ivo Wetzel

Solution #3

The distinction between accessing the name and tying it to a scope is this.

You have access to both global and local scope if you’re only looking for a variable to read its value.

If you assign to a variable whose name isn’t in local scope, you’re binding that name into this scope (and hiding any global names that have the same name).

If you wish to assign to the global name, you must tell the parser to utilize it instead of binding a new local name, which is what the ‘global’ keyword accomplishes.

Binding anywhere within a block enables the name to be bound everywhere in that block, which can have some strange results (e.g. UnboundLocalError suddenly appearing in previously working code).

>>> a = 1
>>> def p():
    print(a) # accessing global scope, no binding going on
>>> def q():
    a = 3 # binding a name in local scope - hiding global
>>> def r():
    print(a) # fail - a is bound to local scope, but not assigned yet
    a = 4
>>> p()
>>> q()
>>> r()
Traceback (most recent call last):
  File "<pyshell#35>", line 1, in <module>
  File "<pyshell#32>", line 2, in r
    print(a) # fail - a is bound to local scope, but not assigned yet
UnboundLocalError: local variable 'a' referenced before assignment

Answered by pycruft

Solution #4

The other responses provide answers to your question. Another thing to remember about names in Python is that they are either local or global depending on the scope.

Consider the following scenario:

value = 42

def doit():
    print value
    value = 0

print value

You can probably guess that the value = 0 statement will be assigning to a local variable and not affect the value of the same variable declared outside the doit() function. You might be even more astonished to learn that the code above doesn’t work. The statement print value inside the function produces an UnboundLocalError.

The reason for this is that Python has observed that you assign the name value somewhere in the function, and value is nowhere declared global. As a result, it’s a local variable. When you try to print it, though, you’ll notice that the local name hasn’t been defined yet. In this scenario, unlike some other languages, Python does not fall back to looking for the name as a global variable. You can’t access a global variable if a local variable with the same name has been defined elsewhere in the function.

Answered by kindall

Solution #5

There is a distinction between accessing a name and assigning a name. In your case, you’re simply looking for a name.

Unless you define a variable global, it is assumed to be local when you assign to it within a function. It is considered to be global in the absence of that.

>>> x = 1         # global 
>>> def foo():
        print x       # accessing it, it is global

>>> foo()
>>> def foo():   
        x = 2        # local x
        print x 

>>> x            # global x
>>> foo()        # prints local x

Answered by user225312

Post is based on