locals()

The built-in locals() function returns a dictionary representing the current local symbol table, which includes variable names as keys and their currently bound references as values. This function is useful for inspecting the state of the local scope within a function or other local contexts:

Python
>>> def add(a, b):
...     result = a + b
...     print(locals())
...     return result
...

>>> add(2, 5)
{'a': 2, 'b': 5, 'result': 7}
7

locals() Signature

Python Syntax
locals()

Arguments

  • The built-in locals() function doesn’t take any arguments.

Return Value

  • Returns a dictionary representing the current local symbol table with variable names as keys and their corresponding values.

locals() Examples

With a function to display local variables:

Python
>>> def func(arg):
...     var = 100
...     print(locals())
...
>>> func(300)
{'arg': 300, 'var': 100}

When called in the global scope:

Python
>>> locals() is globals()
True

locals() Common Use Cases

The most common use cases for the locals() function include:

  • Debugging to inspect variables and their values within a function
  • Dynamically accessing and manipulating local variables, although direct modifications to the dictionary should be avoided
  • Understanding the scope and lifetime of variables within functions

locals() Real-World Example

You might want to log the state of local variables for debugging purposes when a function fails:

Python
>>> def safe_divide(a, b):
...     try:
...         result = a / b
...     except ZeroDivisionError:
...         print("Error: Division by zero")
...         print("Local variables:", locals())
...         return None
...     return result
...

>>> safe_divide(10, 0)
Error: Division by zero
Local variables: {'a': 10, 'b': 0}

In this example, the locals() function provides a snapshot of the local variables when an error occurs, which can be invaluable for debugging.

Tutorial

Namespaces and Scope in Python

In this tutorial, you'll learn about Python namespaces, the structures used to store and organize the symbolic names created during execution of a Python program. You'll learn when namespaces are created, how they are implemented, and how they define variable scope.

basics python

For additional information on related topics, take a look at the following resources:


By Leodanis Pozo Ramos • Updated Nov. 21, 2024 • Reviewed by Dan Bader