When I was reading the code of the template engine Jinja
for Python, an unfamiliar function calledlocals ()
was used, so I checked it, so make a note of it.
locals ()
?Excerpt from Reference
Updates and returns a dictionary representing the current local symbol table. Free variables are returned when you call locals () in a function block, but not in a class block. Note that at the module level, locals () and globals () are the same dictionary.
I interpreted it as returning the local variables that were defined when locals ()
was executed.
Start the interpreter as a test and check the behavior of locals ()
.
>>> a = 1
>>> def sample(b="2", c=True):
... d = 4
... l = locals()
... print(l)
... print(type(l))
...
>>> sample()
{'b': '2', 'c': True, 'd': 4}
<class 'dict'>
Since ʻa, which is out of scope, was not acquired and the variable defined in the
sample` method was acquired, the interpretation of reading the reference seems to be inconsistent.
locals ()
in jinja
jinja
provides a ʻoverlay` method that overrides the instance's configuration information.
When I was reading the method of ʻoverlay,
locals ()` was used as follows.
jinja/src/jinja2/environment.py
# https://github.com/pallets/jinja/blob/737a4cd41d09878e7e6c584a2062f5853dc30150/src/jinja2/environment.py#L385-L428
def overlay(
self,
block_start_string=missing,
# ...abridgement...
bytecode_cache=missing,
):
# ...abridgement...
args = dict(locals())
# ...abridgement...
for key, value in iteritems(args):
if value is not missing:
setattr(rv, key, value)
There are many arguments for ʻoverlay, but it is implemented in a smart process so that it is combined into ʻargs
usinglocals ()
and only the values specified by the caller are updated.
From the above, I feel that locals ()
is suitable for the next process or processing such as jinja
that retrieves only the specified value from the caller by combining a large number of arguments into one dict
. I did.
Below is my own summary.
--locals ()
can get the local variables defined by the time of locals ()
execution with dict
--Can be used when you want to process a large number of arguments in a dict
That's it. If you make a mistake in the written content or interpretation, or if you have any other uses or bat know-how, please comment. : pray:
Recommended Posts