Python locals()

Anonymous contributor's avatar
Anonymous contributor
Published Oct 4, 2024
Contribute to Docs

The locals() built-in function in Python returns a dictionary containing the current local symbol table, which maps variable names to their values in the current scope.

  • Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
    • Includes 6 Courses
    • With Professional Certification
    • Beginner Friendly.
      75 hours

Syntax

locals()

Example

The following example demonstrates the usage of the locals() function:

def example1():
print( "No local variables." , locals() )
def example2():
ex= "A"
print( "One local variable." , locals() )
example1()
example2()

The code above generates the following output:

No local variables. {}
One local variable. {'ex': 'A'}

Note: locals() cannot change the local symbol table. It only allows seeing it.

Codebyte Example

Run the following code to understand how the locals() function works:

Code
Output
Loading...

All contributors

Contribute to Docs

Learn Python on Codecademy

  • Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
    • Includes 6 Courses
    • With Professional Certification
    • Beginner Friendly.
      75 hours