What is Scope in Python
A scope defines the hierarchical order in which the namespaces have to be searched in order to obtain the mappings of name-to-object(variables). It is a context in which variables exist and from which they are referenced. It defines the accessibility and the lifetime of a variable. Let us take a simple example as shown below:
Python3
pi = 'outer pi variable' def print_pi(): pi = 'inner pi variable' print (pi) print_pi() print (pi) |
Output:
inner pi variable outer pi variable
The above program gives different outputs because the same variable name pi resides in different namespaces, one inside the function print_pi and the other in the upper level. When print_pi() gets executed, ‘inner pi variable‘ is printed as that is pi value inside the function namespace. The value ‘outer pi variable‘ is printed when pi is referenced in the outer namespace. From the above example, we can guess that there definitely is a rule which is followed, in order in deciding from which namespace a variable has to be picked.
Scope Resolution in Python | LEGB Rule
Here, we will discuss different concepts such as namespace, scope, and LEGB rule in Python.