Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When is the locals dictionary set?

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?

like image 972
Right leg Avatar asked Sep 07 '17 12:09

Right leg


1 Answers

The namespace of a module is the global namespace, accessed through globals(). There is no separate locals namespace, so locals(), 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 the locals() dictionary. The dictionary returned by locals() 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.

like image 75
Martijn Pieters Avatar answered Sep 28 '22 00:09

Martijn Pieters