Inspect Namespaces with globals, locals and vars
Core idea
A namespace associates names with objects. globals() returns the dictionary of the current module namespace. locals() reports the current local namespace. vars() without an argument behaves like locals(); with an object it returns that object’s __dict__ when available. Inspect only known, nonsensitive names.
rate = 3def inspect(count): total = count * rate print(locals()["total"]) print(globals()["rate"])inspect(4)The local mapping contains total; the module dictionary contains rate.
Compare vars without an argument
def inspect(): label = "A" print(vars()["label"]) print(locals()["label"])inspect()Both calls report the current local binding. vars(obj) instead inspects an object dictionary, a topic covered later.
Python 3.13: local snapshots
def inspect(): count = 1 snapshot = locals() snapshot["count"] = 9 print(count) count = 2 print(snapshot["count"], locals()["count"])inspect()In Python 3.13, an ordinary function receives a fresh dictionary from each locals() call. Changing the dictionary does not rebind the function variable. The old snapshot does not track later assignments.
Common mistake
Do not assume locals() is writable function state. Python 3.13 specifies optimized-scope snapshot behavior; at module scope locals() and globals() refer to the same namespace. Never dump a real namespace containing secrets.
Practice
Write a function with two parameters and one local calculation. Inspect only the calculation by name using locals(), then change the calculation and obtain a fresh snapshot.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Inspect namespaces safely
Check your understanding of namespace inspection.
What is printed?
count = 4def f(count): print(globals()["count"])f(8)What is printed?
def f(): value = 7 print(vars()["value"])f()On Python 3.13, what is printed?
def f(): value = 3 snapshot = locals() snapshot["value"] = 10 print(value)f()What is a suitable debugging practice?