The locals function in Python modifies and retrieves the dictionary that represents the current local symbol table. A symbol table can be described as a data structure that holds all vital information pertaining to the program. This encompasses variable names, methods, classes, and more.
Python local Function Syntax
It has the following syntax:
locals()
Parameters
It does not contain any parameters.
Return
It provides the dictionary corresponding to the current local symbol table.
Different Examples for Python locals Function
In this section, we will explore multiple instances of the Python locals function.
Python locals Function Example 1
The following example demonstrates how the locals function operates within a local scope.
def localsAbsent():
return locals()
def localsPresent():
present = True
return locals()
print('localsNotPresent:', localsAbsent())
print('localsPresent:', localsPresent())
Output:
localsAbsent: {}
localsPresent: {'present': True}
Explanation:
The preceding illustration modifies and returns the dictionary representing the present local symbol table.
Python locals Function Example 2
The following example demonstrates the method for modifying the values within the locals dictionary.
def localsArePresent():
present = True
print(present)
locals()['present'] = False;
print(present)
localsArePresent()
Output:
True
True