Skip to content

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:

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

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

locals() Signature

Language: 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:

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

When called in the global scope:

Language: 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
  • Inspecting local variables and their current values during execution. Note that in a function scope, locals() returns a fresh snapshot dictionary as specified by PEP 667 in Python 3.13 and later, so writing to this dictionary does not modify the actual local variables.
  • 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:

Language: 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 in Python

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

intermediate python

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


By Leodanis Pozo Ramos • Updated June 15, 2026 • Reviewed by Dan Bader