The problem of shadowing
Reading the value of global variables is not a problem in general, but one thing may make it problematic. If a local variable or parameter exists with the same name as the global variable you want to access, you can't do it directly. The global variable is shadowed by the local one.
If needed, you can still gain access to the global variable by using the function globals.
>>> def combine(parameter):
print parameter + globals()['parameter']
...
>>> parameter = 'berry'
>>> combine('Shrub')
Shrubberry
Here from the use of globals(), we can view the namespace as a dictionary but with the mark of list "[ ]"
Rebinding global variables (making them refer to some new value) is another matter. If you assign a value to a variable inside a function, it automatically becomes local unless you tell Python otherwise.
>>> x = 1
>>> def change_global():
global x
x = x + 1
>>> change_global()
>>> x
2
Nested scopes
Nesting is normally not all that useful, but there is one particular application that stands out: using one function to "create"another. This means that you can (among other things) write functions like the following:
def multiplier(factor):
def multiplyByFactor(number):
return number*factor
return multiplyByFactor
One function is inside another, and the outer function returns the inner one; that is, the function itself is returned—it is not called.
What's important is that the returned function still has access to the scope where it was defined; in other words, it carries its environment (and the associated local variables) with it!
Because of Python's nested scopes, this variable from the outer local scope (of multiplier) is accessible in the inner function later on, as follows:
>>>double = multiplier(2)
>>>double(5)
10
>>>multiplier(5)(4)
20