BlogsDope image BlogsDope

Python locals() function

March 12, 2021 PYTHON FUNCTION 593

The built-in utility functions provided by Python help us in performing many tasks easily and the Python locals() function is one of these methods. This method updates and then returns the a dictionary of the current local symbol table.

Python locals() Syntax

The following is the syntax of the locals() method:

locals()

locals() Parameters

The locals() method does not take any parameter as an argument.

locals() Return Value

The locals() function returns a dictionary of the current local symbol table. This dictionary consists of all the local scope variables as well as other symbols for the current program that are stored in the current local symbol table. 

  • Symbol Table: A symbol table is a data structure that is maintained by the compiler and it contains all the necessary information about the program such as variable names, methods, classes, etc.
  • Local Symbol Table: Local symbol table contains all the information related to the local scope of the program, and is accessed in Python using locals() method. A local scope can be within a function, within a class, etc.

Python locals() Examples

Example 1:

In the below example we can see that the locals() method can only access the local scope variables and not the global variables.

# global variables
a = 50
b = 60

def myFunc():
    # local variable
    s = 100
    print(locals())
myFunc()

Output:

{'s': 100}

Example 2:

Unlike the globals() function, the locals() function cannot modify the value of an item in the local symbol table as shown in the below example:

def myFunc():
    # local variable
    s = 100
    print("Before change the value of s is:",s)
    locals()['s'] = 10;
    print("After change the value of s is still:",s)
    
myFunc()

Output:

​Before change the value of s is: 100
After change the value of s is still: 100

In this way we have seen the working of the Python locals() function and how it can be used to access the local variables and the local symbol table.


Liked the post?
Zealous Learner.
Editor's Picks
0 COMMENT

Please login to view or add comment(s).