Understanding the Python locals() Function
Learn what Python's locals() returns, how scope changes its behavior, why writes to it fail, and when to use it for debugging and template context.

locals() is a built-in Python function that returns a mapping representing the current local symbol table: the names of local variables mapped to their current values. It is one of the introspection tools Python exposes, and it behaves differently depending on where it is called. Understanding those differences matters because the common assumption — that locals() gives you a live, writable view of local variables — is wrong in CPython.
What locals() Actually Returns
When called inside a function, locals() builds a mapping from the local variables that exist at that point in execution.
def example():
name = "ada"
count = 3
print(locals())
example()The output is {'name': 'ada', 'count': 3}. The mapping contains only the names that are currently bound in the local scope. If a variable is defined after the call, it will not appear in the result from the earlier call.
The keys are always strings, and the values are the current object references. This makes locals() convenient for inspection, but it is not a live view.
How Scope Changes the Result
The behavior of locals() depends on the scope in which it is evaluated.
At module level, locals() returns the same dictionary as globals():
# module level
print(locals() is globals()) # TrueInside a class body, locals() returns the namespace that is being constructed for the class. This is why you will sometimes see locals() used inside class definitions to build a dictionary of class attributes.
Inside a function, locals() returns a separate mapping that reflects the function's local variables at the moment of the call. The important distinction is that at module level the returned mapping is the actual namespace, while inside a function it is a snapshot.
Why Modifying the Returned Dictionary Fails
The most common mistake with locals() is trying to use it to set local variables. Depending on CPython version, the write may be silently ignored or may raise TypeError; it does not change the live local variable.
def broken():
x = 10
d = locals()
d['x'] = 99
print(x) # still 10 in versions where the write is acceptedThe assignment to d['x'] does not change the local variable x. In CPython, local variables in a function are stored in an array of slots on the frame, not in a dictionary. The locals() call builds a new mapping from those slots each time it is invoked. Writing to that mapping is not a reliable way to change local variables.
This is a CPython implementation detail, but it is the behavior that virtually all Python developers will encounter. The language specification does not guarantee that locals() returns a live mapping, and code that relies on writing to it is not portable.
Practical Uses for locals()
The main legitimate use of locals() is read-only introspection. It is useful for logging the current state of a function for debugging, building a context dictionary for a template engine, or passing the current scope to a helper that needs to inspect names.
def process_order(order_id):
status = "pending"
attempts = 0
logger.debug("order state: %s", locals())Because locals() captures the current values, it is a quick way to snapshot the state of a function without listing each variable manually.
Closures and Nested Functions
Free variables add a small twist. Inside a nested function, locals() can include values captured from the enclosing scope, because those free variables are part of the inner function's symbol table. The entry is still a copy: updating locals()['value'] will not change the cell used by the closure.
def outer():
value = 42
def inner():
print(locals()) # includes 'value' as a free variable
return value
inner()Even though value is not assigned inside inner, it is visible to inner, and locals() reports it. The practical caution remains the same: the returned mapping is for inspection, not for writes.
Performance Cost of Calling locals()
Each call to locals() inside a function allocates a new mapping and copies the current local variable bindings into it. In a tight loop, this allocation happens on every iteration:
def hot_loop():
total = 0
for i in range(1000):
total += i
# avoid doing this in the loop
_ = locals()
return totalThe cost is proportional to the number of local variables in the frame. For a function with a handful of locals, the overhead is small but not free. If locals() is called thousands of times per request, the allocations add up. Prefer calling it once at the end of a function, or avoid it entirely in performance-sensitive paths.
Alternatives: vars(), globals(), and inspect
vars() is closely related. Without an argument, vars() acts like locals(), including inside a function; it does not require a __dict__ attribute. With an object argument, vars(obj) returns obj.__dict__ when the object has one, and raises TypeError otherwise.
globals() returns the module-level namespace and is always a live dictionary. Writing to globals() does affect the module, which is why it is sometimes used for dynamic configuration, though it is rarely a good idea.
For deeper frame inspection, inspect.currentframe() returns the current frame object, and inspect.getargvalues() can summarize a frame's arguments. These are useful in debuggers and profilers but carry more overhead and are not intended for application code.
A Template Context Pattern and Its Pitfall
A common pattern is to build a template context from locals():
def render_user(user, items):
title = "User page"
context = locals()
return template.render(**context)This works as long as every variable that the template needs is already bound before the locals() call. If you add a variable after the call, it will not be in the context:
def render_user(user, items):
context = locals()
title = "User page" # too late
return template.render(**context)The title variable is missing from context because locals() was called before title was assigned. The same problem appears if a variable is rebound after the call. This makes locals() a fragile way to build contexts: the order of statements changes the result. An explicit dictionary or keyword arguments are more predictable and easier to maintain.
Try matching browser tools
All toolsSmall utilities that fit Python work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Python guides
All Python guidesPython iter(): How the Built-in Function Works
Explains Python's iter() built-in: how it creates iterators, the two-argument sentinel form, custom iterator classes, and common edge cases.
Python Pika: Queues, Exchanges, Routing Keys, and Acknowledgements
Learn how to use Python's Pika client with RabbitMQ: declare queues and exchanges, publish with routing keys, consume messages, and handle acknowledgements reliably.
Python Kafka: kafka-python vs Confluent Client
python kafka python vs confluent kafka: Compare kafka-python and Confluent Kafka Python clients: API differences, performance, feature coverage, and when to choose eac...
Python Kafka Offsets, Partitions, and Manual Commits
Learn how Kafka offsets and partitions work and how to manually commit offsets in Python consumers with kafka-python and confluent-kafka. Covers sync vs async commits, rebalances, and seeking.
More in Python
All Python guidesThe guides filed next to this one in Python, in library order.