You can learn about Python Variable Scope Programs with Outputs helped you to understand the language better.

Python Programming – LEGB Rule

We know that variables need to be defined before they can be used in a program. Depending on how and where it was defined, a variable will have to be accessed in different ways. Some variables are defined globally, and others locally. This means that a variable referring to an entity in a certain part of a program may refer to something different in another part of the program. Depending on where you are in a program, a different namespace will be used.

The “scope” defines on which hierarchy level Python searches for a particular “variable name” for its associated object. It uses the LEGB-rule to search the different levels of namespaces before it finds the name-to-object’ mapping. LGB stands for Local Enclosed Global Built-in. LGB tells us the order in which Python accesses the variable in a program. First, Python will check if the variable is present in the local scope, if not then checks in enclosing scope. If the search in the enclosed scope is unsuccessful, too, Python moves on to the global namespace, and finally, it will search the built-in namespace:
Local -> Enclosed -> Global -> Built-in, where the arrows denote the direction of the namespace-hierarchy search order. (See Figure 12.10).

Python Programming - LEGB Rule chapter 12 img 1

Python namespaces can be divided into four types. Let’s understand the LEGB terms one by one:

Local

Local can be inside a function or class method. A function, for-loop, try-except block are some examples of a local namespace. The name references create or change Local names by default. Python first tries to search for an identifier(variable) in the Local scope. The local variable exists only within the block/function that it is declared in. The local namespace is deleted when the function or the code block finishes its execution. You cannot use it outside the function where it is declared. For example in the code given in Figure 12.11, x=5 is local to the num( ) function means you cannot access that variable outside this function. So, the output of the last print(x) will be an error saying the name ‘x’ is not defined.

Example
Demo of Local namespace.

# Demo of Local namespace
def num( ):
x=5
print(x)
num ( )
print (x)RUN
>>>
5
Traceback (most recent call last):
File “C:/Users/shash/AppData/Local/Programs/Python/Python37-32/local.py”, line 5, in <module>
print (x)
NameError: name ‘x’ is not defined
>>>

Enclosed

Enclosed can be its enclosing function, i.e., if a function is wrapped inside another function. Python checks the enclosing feature, such as if there is a variable with the same name. If Python does not find an identifier(variable) within the local scope, it will examine the Enclosing scope to see if it can find the variable there. Its lifecycle is the same as the local namespace. Let’s understand this by an example discussed in Figure 12.12.

Example
Demo of Enclosed namespace.

# Demo of Enclosed namespace
def outside( ):
x=5
def inside():
print( x)
inside( )
print (x)
outside( )RUN
>>>
5
5
>>>

Global

Global refers to the uppermost level. If you define a variable at the top of your script, it will be a global variable. This means that it is accessible from anywhere in your script, including from within a function. The global namespace for a module is created when the module definition is read. Generally, module namespaces also last until the interpreter quits. If Python fails to find the variable in both above scopes, then it will check the global scope. Let’s understand this by an example discussed in Figure 12.13. As you have no x in the local and enclosing scope, so Python checks the global scope and outputs 5 for both print x statements.

Example
Demo of Global namespace.

#Demo of Global namespace
x=5
def outside ( ):
def inside():
print (x)
inside ( )
print( x)
outside ( )RUN
>>>
5
5
>>>

Let’s Try

Write the output of the following code where global variable name can be changed by change_name ( ):

name = ‘Mohan’
def change_name(newname):
global name
name = new_name
print(name)
change_name(‘Sohan’)
print(name)

Built-in

Built-in are special names that Python reserves for itself. Built-in means the function and variables that are already defined in Python. If an identifier is not found in any of the above scopes within a module, then Python will examine the built-in identifiers to see if it is defined there.

Example
Demo of Built-in namespace.

# Demo of Built-in namespace
x = len ( ‘VIVEK’ )
print(x)RUN
>>>
5
>>>

If len is not found in any of the scopes, then Python would consult the Built-in scope, where it will find the len function and outputs 5. But if you create your own len function then it will have precedence over the Built-in len function. Let’s see example 14.

Example
Demo of Built-in namespace.

#Demo of Built-in namespace
def len(x):
return (1)
x = len ( ‘VIVEK’ )
print(x)RUN
>>>
1
>>>

Note that your len function precedes over built-in len and thus the output of print x statement equals 1.

Leave a Reply

Your email address will not be published. Required fields are marked *