Check the scope of local variables with the Python locals function.

Overview

Check the scope of local variables with the Python locals function.

Check result

locals()

From help

locals()
    Return a dictionary containing the current scope's local variables.

    NOTE: Whether or not updates to this dictionary will affect name lookups in
    the local scope and vice-versa is *implementation dependent* and not
    covered by any backwards compatibility guarantees.

Code used for confirmation

I feel unfamiliar with Python. .. .. ..


g0_val = "g0"

def func1():
    func1_val = "f1"
        
class Class1():
    class1_val = "c1"
    
def func2():
    func2_val = "f2"
    
    class Class2():
        class2_val = "c2"
        print("class2-locals",locals())
        
    for y2 in range(1):
        range2_val = "r2"
    
    def func3():
        func3_val = "f3"
        
        class Class3():
            class3_val = "c3"
            
        for y3 in range(1):
            range3_val = "r3"
            
        print("fun3-locals",locals())
    
    func3()        
    print("fun2-locals",locals())
    
func1()
func2()


It became as follows.

C:\_qiita\python_etc\_locals>python test_locals.py
class2-locals {'__module__': '__main__', '__qualname__': 'func2.<locals>.Class2', 'class2_val': 'c2'}
fun3-locals {'func3_val': 'f3', 'Class3': <class '__main__.func2.<locals>.func3.<locals>.Class3'>, 'y3': 0, 'range3_val': 'r3'}
fun2-locals {'func2_val': 'f2', 'Class2': <class '__main__.func2.<locals>.Class2'>, 'y2': 0, 'range2_val': 'r2', 'func3': <function func2.<locals>.func3 at 0x000002B3CED922F0>}

What I was able to confirm

The following was confirmed.

If you express it in words ** Only functions and classes have block scope ** Is not it.

I hope it is expressed by a proper noun. .. ..

Summary

Nothing in particular. If you have any comments, please let us know.

(What I really wanted to consider was what would happen if I moved a lot of the code to a function. Perhaps, if I didn't do anything special, I just felt that the scope was local and that wasn't a problem. )

Recommended Posts

Check the scope of local variables with the Python locals function.
Check the date of the flag duty with Python
Check the behavior of destructor in Python
[Python3] Rewrite the code object of the function
[python] Checking the memory consumption of variables
Check the path of the Python imported module
The story of manipulating python global variables
[python] Check the elements of the list all, any
2016 The University of Tokyo Mathematics Solved with Python
[Note] Export the html of the site with python.
Get the caller of a function in Python
Calculate the total number of combinations with python
Convert the character code of the file with Python3
[Python] Determine the type of iris with SVM
Usage of Python locals ()
the zen of Python
Domain check with Python
Local server with python
Check version with python
Easy way to check the source of Python modules
Extract the table of image files with OneDrive & Python
Learn Nim with Python (from the beginning of the year).
[Introduction to Python] How to iterate with the range function?
Destroy the intermediate expression of the sweep method with Python
Visualize the range of interpolation and extrapolation with python
Calculate the regression coefficient of simple regression analysis with python
Summary of the basic flow of machine learning with Python
14 quizzes to understand the surprisingly confusing scope of Python
Get the operation status of JR West with Python
Extract the band information of raster data with python
Check the asymptotic nature of the probability distribution in Python
I tried to find the entropy of the image with python
Try scraping the data of COVID-19 in Tokyo with Python
I tried "gamma correction" of the image with Python + OpenCV
Try to get the function list of Python> os package
Towards the retirement of Python2
The story of implementing the popular Facebook Messenger Bot with python
Unify the environment of the Python development team starting with Poetry
Create a local scope in Python without polluting the namespace
Visualize the results of decision trees performed with Python scikit-learn
Check the operation of Python for .NET in each environment
Check python coverage with pytest-cov
[python] Value of function object (?)
Calculate the square root of 2 in millions of digits with python
Python --Check type of values
Tank game made with python About the behavior of tanks
[Python] Etymology of python function names
Run the intellisense of your own python library with VScode.
Check the memory status of the server with the Linux free command
About the ease of Python
Have the equation graph of the linear function drawn in Python
About the enumerate function (python)
I evaluated the strategy of stock system trading with Python.
Consideration for Python decorators of the type that passes variables
Let's touch the API of Netatmo Weather Station with Python. #Python #Netatmo
I made a function to check the model of DCGAN
Check the operating status of the server with the Linux top command
[Python3] Call by dynamically specifying the keyword argument of the function
The story of rubyist struggling with python :: Dict data with pycall
[Homology] Count the number of holes in data with Python
Try to automate the operation of network devices with Python