Python locals Function with Examples

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:

Example

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.

Example

def localsAbsent():

    return locals()

def localsPresent():

    present = True

    return locals()

print('localsNotPresent:', localsAbsent())

print('localsPresent:', localsPresent())

Output:

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.

Example

def localsArePresent():

    present = True

    print(present)

    locals()['present'] = False;

    print(present)

localsArePresent()

Output:

Output

True

True

Input Required

This code uses input(). Please provide values below: