nik nik - 1 month ago 4x
Python Question

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


I'm using Python 2.7 and I tried this little test

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

It seems things are working fine even without
. I was able to access global variable without any problem.

Am I missing anything? Also, following is from Python documentation:

Names listed in a global statement
must not be defined as formal
parameters or in a for loop control
target, class definition, function
definition, or import statement.

While formal parameters and class definition make sense to me, I'm not able to understand the restriction on for loop control target and function definition.


The keyword global is only useful to change or create global variables in a local context, although creating global variables is seldom considered a good solution.

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

print me     # Asking for a global variable

The above will give you:

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

While if you use the global statement, the variable will become available "outside" the scope of the function, effectively becoming a global variable.

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

print me     # Asking for a global variable

So the above code will give you:

locally defined
locally defined

In addition, due to the nature of python, you could also use global to declare functions, classes or other objects in a local context. Although I would advise against it since it causes nightmares if something goes wrong or needs debugging.