[PYTHON] Look up the names and data of free variables in function objects

I wrote about closures earlier in This Nested Function Definition Use Case Article, but the names and values of free variables are for function objects. I tried to find out how it is stored inside. (Hereafter, Python 3 is assumed.)

Free Python variables are variables that are used in a block of code (not global variables) but are not defined within that block and Description /reference/executionmodel.html).

For example, in the code below, the variable y is used inside a nested bar function, but it is defined inside the definition block of the outer foo function. So y is a local variable of the function foo and a free variable of the bar function.

python


def foo():
    
    y = "I'm free in bar."

    def bar():
        print(y)
        
    y = "I'm still free in bar."

    return bar

foo returns bar, so to call bar you need two parentheses like this:

python


>>> foo()()
I'm still free in bar.

By the way, the value of y is not the time when bar is defined, but the value when it is called. In the above example, y is defined twice in foo, but you can see that it is a string defined later.

Now, as for the main subject, on the outer function foo object side, the variable name y used from the nested function is in the co_cellvars member (tuple) of its own code object ( __code__). I am.

python


>>> foo.__code__.co_cellvars
('y',)

On the other hand, on the bar object side, y is named as a free variable in the co_freevars member of the code object. (The foo () below is bar.)

python


>>> foo().__code__.co_freevars
('y',)

The contents of the free variable are contained in the tuple of the __closure__ attribute as a cell object, and can be obtained as cell_contents as follows.

python


>>> foo().__closure__[0].cell_contents
"I'm still free in bar."

Recommended Posts

Look up the names and data of free variables in function objects
Separation of design and data in matplotlib
Python variables and data types learned in chemoinformatics
Get the caller of a function in Python
Organize the meaning of methods, classes and objects
Fix the argument of the function used in map
The story of reading HSPICE data in Python
The simplest Python memo in Japan (classes and objects)
Full-width and half-width processing of CSV data in Python
Extract and list personal names and place names in the text
Difference between Ruby and Python in terms of variables
About the inefficiency of data transfer in luigi on-memory
Select the required variables in TensorFlow and save / restore
Not being aware of the contents of the data in python
Let's use the open data of "Mamebus" in Python
Try scraping the data of COVID-19 in Tokyo with Python
[Blender] Know the selection status of hidden objects in the outliner
See the power of speeding up with NumPy and SciPy
Analyzing data on the number of corona patients in Japan
Have the equation graph of the linear function drawn in Python
Reference order of class variables and instance variables in "self. Class variables" in Python
Search for variables in pandas.DataFrame and get the corresponding row.
[Homology] Count the number of holes in data with Python
Listed data structures in the Linux kernel and their operations
Make the function of drawing Japanese fonts in OpenCV general
[Tips] Problems and solutions in the development of python + kivy
What beginners learned from the basics of variables in python
I sent the data of Raspberry Pi to GCP (free)
I tried fitting the exponential function and logistics function to the number of COVID-19 positive patients in Tokyo
About Python variables and objects
[Python] Etymology of python function names
Equivalence of objects in Python
Beginning of Nico Nico Pedia analysis ~ JSON and touch the provided data ~
Scraping the schedule of Hinatazaka46 and reflecting it in Google Calendar
Try transcribing the probability mass function of the binomial distribution in Python
About Boxplot and Violinplot that visualize the variability of independent data
Probability of getting the highest and lowest turnip prices in Atsumori
Organize useful blogs in the field of data science (overseas & Japan)
Feel free to change the label of the legend in Seaborn in python
Notify the contents of the task before and after executing the task in Fabric
A function that measures the processing time of a method in python
Clean up the repository at the end of the year and delete DS.store
Dig the directory and create a list of directory paths + file names
Create a function to get the contents of the database in Go
Verify the compression rate and time of PIXZ used in practice
Get the title and delivery date of Yahoo! News in Python
Set up a dummy SMTP server in Python and check the operation of sending from Action Mailer
Use Cloud Dataflow to dynamically change the destination according to the value of the data and save it in GCS
When tkinter is started in another thread, the thread itself should stop and clean up the variables before terminating the thread.