Python locals Function with Examples - Python Tutorial | Logic Practice
Python Course / Other / Python locals Function with Examples

Python locals Function with Examples

BLUF: This lesson on Python locals Function with Examples provides a comprehensive guide to understanding and implementing this concept in Python. Whether you're a beginner or looking to refresh your knowledge, you'll find clear explanations and interactive code examples here.
Key Concept: Python locals Function with Examples

Mastering Python locals Function with Examples is essential for building efficient Python applications. Focus on the syntax and the best practices highlighted in this tutorial.

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:

Logic Practice
Install Logic Practice
Add to home screen for a faster app-like experience