Python locals() Function



The Python locals() function is a built-in function that returns a dictionary representing the current local symbol table. It provides access to all the local variables, functions, and their corresponding values. Note that the symbol table is created by Python compiler prior to the execution of the given code.

In Python, each program has a symbol table that contains information about the names (variables, functions, classes, etc.) defined in the program. The symbol table is represented by a dictionary, where the names are the keys, and the associated values represent their current values or references.

Syntax

Following is the syntax of the Python locals() function −

locals()

Parameters

The Python locals() function does not accept any parameters.

Return Value

The Python locals() function returns a dictionary representing the local symbol table.

Examples

Now, let's see some examples of locals() function −

Example 1

The locals() function can be used to track local variables in a given function. The code below will display all local variables currently in the scope.

def localFun():
   localVar1 = 112
   localVar2 = "TutorialsPoint"
   print(locals())

print("The local attributes of the given functions are:")
localFun()

Following is an output of the above code −

The local attributes of the given functions are:
{'localVar1': 112, 'localVar2': 'TutorialsPoint'}

Example 2

The changes made to the dictionary returned by locals() function are ignored, which means they do not affect the values of local variables. This is why when we do modifications to the local variables, it will not affect the local variable. In this example, we can see the before and after affect of modification.

def localFun():
   localVar = 56
   print("Before modifying:", localVar)
   locals()["localVar"] = 26
   print("After modifying:", localVar)

localFun()

Output of the above code is as follows −

Before modifying: 56
After modifying: 56

Example 3

The code below demonstrates how to see the working of local variables and instance variables within a class function with the help of locals() function. This code will return a dictionary with "self" as a key, pointing to the instance of given class.

class LocalClass:
   def localMethod(self):
       self.localVar = 100
       print(locals())

obj = LocalClass()
obj.localMethod()

Following is an output of the above code −

{'self': <__main__.LocalClass object at 0x7b1718cc2fd0>}

Example 4

We can also use the locals() function with the lamda expressions. Here, we have created a lambda expression which returns its local variable.

localLambda = lambda loclaVar: locals()
print(localLambda(52))

The above program, on executing, displays the following output −

{'loclaVar': 52}
python_built_in_functions.htm
Advertisements