Updated: Jan 28
The variable scope (or namespace) is a very fundamental concept in programming languages.
following questions appeared lots of times in interviews for python developers.
What is LEGB Rule?
Explain Python variable scope (or namespace)?
Difference between global and nonlocal variables in python?
A namespace is a system that has a unique name for each and every object in Python. An object might be a variable or a method. Python itself maintains a namespace in the form of a Python dictionary.
Python follows LEGB Rule, in variable scope (or namespace)
Local Variables (L) Variables defined inside a function.
Enclosed variables (E) Variables in the context of nested functions variables defined in outer_func(), will be accessed by inner_func()
Global Variables (G) Variables defined outside of the function.
Built-in Variables (B) Variables defined in Python Built-in modules.
When an identifier/name is called in a program the correspond variable will be retrieved sequentially in the local, enclosing, global and built-in scope. If the naming variable exists, then the first occurrence of it will be used.
if we want to modify the global name variable in the function, a statement with the global keyword is needed.
Nonlocal (or) Enclosing variable.
The concept of enclosing variables is mentioned in the context of nested functions. For inner functions, the variables of outer functions are neither local variables nor global variables, they are called enclosing (or) nonlocal variables.
As shown above, three different names represent three different types of variables and they are called by the LEGB rule. If we would like to change a nonlocal variables value in the inner function a nonlocal keyword is needed
The LEGB rule defines the order in which Python looks up its variables. If we want to change a global variable in a function, the global statement is needed. If we want to change a nonlocal or enclosing variable in an inner function, a nonlocal statement is needed.