locals() is a built-in Python function that returns a dictionary representing the current local symbol table — all variables, parameters, and nested functions defined in the current scope (function, class body, or module). It provides runtime access to the local namespace, enabling dynamic inspection, modification, and metaprogramming. In 2026, locals() remains a powerful debugging and introspection tool in data science (inspecting function variables in pandas/Polars/Dask pipelines), software engineering (dynamic variable creation, debugging decorators), and interactive environments (Jupyter, IPython) — offering a live view into the local environment while requiring careful use to avoid namespace pollution or unexpected side effects.
Here’s a complete, practical guide to using locals() in Python: basic inspection & modification, real-world patterns (earthquake dynamic variable creation, debugging pipelines, config injection), and modern best practices with type hints, safety, performance, and alternatives (globals(), vars(), inspect, locals() in comprehensions).
Basic locals() — inspect and interact with the local namespace inside functions.
def process_earthquake(mag: float, place: str):
depth = 25.0
is_strong = mag >= 7.0
local_vars = locals()
print("Local variables:", local_vars)
# {'mag': 7.2, 'place': 'Japan', 'depth': 25.0, 'is_strong': True}
# Modify local variable dynamically
local_vars['depth'] = 30.0
print(depth) # 30.0 (changed!)
process_earthquake(7.2, "Japan")
Real-world pattern: dynamic variable creation & debugging in data analysis functions.
def analyze_quakes(df, threshold=7.0):
strong = df[df['mag'] >= threshold]
count = len(strong)
max_mag = strong['mag'].max()
# Dynamically create variables from results
locals_dict = locals()
for key, value in {
'strong_count': count,
'max_magnitude': max_mag,
'mean_depth': strong['depth'].mean()
}.items():
locals_dict[key] = value
# Inspect all locals
print("Analysis locals:", {k: v for k, v in locals_dict.items() if not k.startswith('_')})
return strong
# Usage
import pandas as pd
df = pd.read_csv('earthquakes.csv')
analyze_quakes(df)
Advanced usage — locals() in comprehensions, classes, and dynamic execution.
# locals() in list comprehension (Python 3.8+ scoped)
def scoped_locals():
result = [locals() for i in range(3)]
return result[0] # locals only contains 'result' and 'i'
print(scoped_locals()) # {'result': [...], 'i': 2}
# Class body: locals() shows class attributes
class QuakeConfig:
threshold = 7.0
print("Class locals:", locals()) # {'__module__': ..., 'threshold': 7.0}
# Dynamic code execution with locals
def run_dynamic(code_snippet: str, context: dict):
local_scope = context.copy()
exec(code_snippet, globals(), local_scope)
return local_scope
result_scope = run_dynamic("x = 10; y = x * 2", {})
print(result_scope) # {'x': 10, 'y': 20}
Best practices for locals() in Python & data workflows. Use locals() sparingly — prefer explicit variables, function returns, or class attributes. Modern tip: use Polars/Dask — avoid heavy reliance on locals in distributed code; use dicts for config. Prefer locals() inside functions — global scope is globals(). Use locals().get('var', default) — safe access. Add type hints — def inspect_locals() -> dict[str, Any]. Avoid modifying locals() — updates may not affect local variables (implementation detail in CPython). Use vars(obj) — for object attributes (__dict__). Use inspect.currentframe().f_locals — advanced local inspection. Use locals() in debugging — print(locals()) to see variables. Use pprint.pprint(locals()) — pretty-print for large namespaces. Use locals() in comprehensions — careful with scope (Python 3.8+). Use locals().update({...}) — batch update (not always reflected). Use del locals()['var'] — remove local (not always effective). Use locals() with exec() — dynamic variable creation. Use locals() in decorators — inspect caller locals. Use locals() in context managers — capture state. Use locals() in generators — inspect generator locals. Use locals() in async functions — inspect async locals. Use locals() in class methods — shows method locals only.
locals() returns the current local namespace as a dictionary — inspect, debug, or dynamically create variables at runtime. In 2026, use for debugging, dynamic config, plugin systems, and interactive pipelines — but prefer explicit state, avoid pollution, and restrict modifications. Master locals(), and you’ll gain deep control over function-local environments while writing safe, maintainable code.
Next time you need to see what’s local — use locals(). It’s Python’s cleanest way to say: “Show me (or change) what’s currently local — right now.”