Scope Rules in Functions
Functions provide a nested namespace (sometimes called a scope), which localizes the names they use, such that names inside the function will not clash with those outside (in a module or other function). We usually say that functions define a local scope, and modules define a global scope.
The LGB Rule:
– Name references search at most three scopes: local, then global, then built-in.
– Name assignments create or change local names by default.
– “Global” declarations map assigned names to an enclosing module’s scope.
In other words, all names assigned inside a function
def statement are locals by default; functions can use globals, but they must declare globals to change them.
When you use an unqualified name inside a function, Python searches three scopes—the local (L), then the global (G), and then the built-in (B)—and stops at the first place the name is found.
When you assign a name in a function (instead of just referring to it in an expression), Python always creates or changes the name in the local scope, unless it’s declared to be global in that function.
An example code is given to further illustrate the concept.
# global scope X = 99 # X and func assigned in module: global def func(Y): # Y and Z assigned in function: locals # local scope Z = X + Y # X is not assigned, so it's a global return Z func(1) # func in module: result=100
X and func are global names because it is assigned at top-level
Y and Z are local names to the function.
Local scope vs global scope
The first example below shows the local scope, new_val within the function, is not related to the global new_val = 10. The local scope uses the value = 3 to calculate the square of the number. As a result, it returns 9 when function square() is called and global new_val did not change.
In my earlier paragraph, “functions can use globals, but they must declare global to change them. ” Below sample illustrates the meaning of this paragraph where,
is declared within the function and now, the new_value = 10 and it calculates the square of the number which returns 100. It does not take the parameter passes in square() function. Here, the new_val has been modified.
And, this looks different that the following sample code, where it takes reference of the global variable new_val = 10 and did not change it within the function after the calculation. It then, reassigns with a new value of new_val = 20 and repeats the function calls.
To use the built-in scope in Python, a module called builtins is needed. After executing the code,
we can execute the next code,
which print a list of all the names in the module builtins. You can find some familiar names within the list.
Summary of the day:
- Python’s scope rules
- global scopes
- local scopes
- built-in scopes