A module holds a dictionary to keep track of itscontext, such as the names defined at some point of the execution. This dictionary can be accessed through vars(module)
(or module.__dict__
) if module
was imported, or by a call to the locals
built-in function in the module itself:
Update and return a dictionary representing the current local symbol table.
But I found myself a bit confused, when I tried accessing the locals dictionary from a function. The output of a script containing only the following is an empty dictionary:
def list_locals():
print(locals())
list_locals()
But on the other hand, if a script contains exclusively the following, the output is the expected dictionary, containing __name__
, __doc__
and the other module-level variables:
print(locals())
So, when is the content of the locals dictionary set?
In addition, what does "update" mean in the definition of the locals
function?
The namespace of a module is the global namespace, accessed through
globals()
. There is no separate locals namespace, solocals()
, outside of functions, just returns the global namespace.Only functions have a local namespace. Note that
locals()
is a one-way reflection of that namespace; the CPython implementation for functions is highly optimised and you can't add or alter local variables through thelocals()
dictionary. The dictionary returned bylocals()
is updated whenever the namespace has changed between calls to that function.Note also that things like list / dict / set comprehensions, generator expressions and class bodies are in reality executed as functions too, albeit with different namespace rules. In such contexts
locals()
will also return the separate function local namespace.