Built-in Functions and Types

locals()

Inspect bindings visible in the current local namespace. In Python 3.13, optimized scopes such as functions return fresh dictionaries on each call: editing the snapshot does not rebind function locals, and later assignments do not update older snapshots. In module and class scopes, the returned namespace mapping is live. Comprehensions and generator expressions have specific scope behavior; avoid using locals to assign function variables.

Formal Syntax & Structure

python syntaxpython
locals()

Return Value

mapping

Current local namespace representation; a fresh snapshot in optimized scopes.

Working Example

Example Snippetpython
def demo():    count = 2    snapshot = locals()    count = 4    snapshot["count"] = 9    print(count)    print(locals()["count"])    print(snapshot["count"])
demo()
Python Reference