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
>>> sub = ['0', '0', '0', '0']
>>> def getJoin():
... return '.'.join(sub)
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.
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 bob() print me # Asking for a global variable
The above will give you:
locally defined Traceback (most recent call last): File "file.py", 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 bob() 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.