Usage of Python locals ()

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.

What is 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.

Where to use 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.

Summary

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

Usage of Python locals ()
[Python] Correct usage of map
Sample usage of Python pickle
Basic usage of Python f-string
[Python] Correct usage of join
[python] Correct usage of if statement
Introduction of Python
Basics of Python ①
Basics of python ①
Copy of python
Introduction of Python
Non-logical operator usage of or in python
[Python] Operation of enumerate
List of python modules
Unification of Python environment
Copy of python preferences
Basics of Python scraping basics
Summary of pyenv usage
Basic usage of flask-classy
Basic usage of Jinja2
the zen of Python
python decorator usage notes
Basic usage of SQLAlchemy
Installation of Python 3.3 rc1
[Python] pytest-mock Usage notes
# 4 [python] Basics of functions
Basic knowledge of Python
Sober trivia of python3
Summary of Python arguments
Basics of python: Output
Installation of matplotlib (Python 3.3.2)
Application of Python 3 vars
[Python] Class type and usage of datetime module
Various processing of Python
[Introduction to Python] Basic usage of lambda expressions
Python --Explanation and usage summary of the top 24 packages
[Introduction to Python] Basic usage of the library matplotlib
Super basic usage of pytest
Towards the retirement of Python2
Summary of python file operations
Summary of Python3 list operations
Python --Quick start of logging
Recommendation of binpacking library of python
Basic usage of PySimple GUI
[python] Value of function object (?)
Python standard unittest usage notes
python * args, ** kwargs Usage notes
Automatic update of Python module
Python --Check type of values
[Python] Etymology of python function names
About the ease of Python
Static analysis of Python programs
About various encodings of Python 3
Equivalence of objects in Python
Convenient usage summary of Flask
Introduction of activities applying Python
python> Handling of 2D arrays
Install multiple versions of Python
Version upgrade of python Anaconda
Handling of python on mac
python: Basics of using scikit-learn ①