Execution order when multiple context managers are specified in the Python with statement

According to Python's Language Reference (https://docs.python.org/3/reference/compound_stmts.html#the-with-statement), with can be multiple context managers.

Language_Excerpt from Reference


with A() as a, B() as b:
    SUITE

This is equivalent to a nested with statement.

Language_Excerpt from Reference


with A() as a:
    with B() as b:
        SUITE

Then, the order in which __exit__ () is called should be the reverse of the order in which they were written (B → A).

I actually wrote a sample and confirmed it.

my_context_manager.py


class MyContextManager:
    def __init__(self, name):
        self.name = name

    def __enter__(self):
        print(f'{self.name} enter')

    def __exit__(self, exc_type, exc_val, exc_tb):
        print(f'{self.name} exit')


with MyContextManager('A') as a, MyContextManager('B') as b:
    print('do something')

Execution result


$ python my_context_manager.py
A enter
B enter
do something
B exit
A exit

Indeed, it is in reverse order.

Recommended Posts

Execution order when multiple context managers are specified in the Python with statement
Manage multiple context managers together with Python contextlib.ExitStack
Turn multiple lists with a for statement at the same time in Python
A memo when checking whether the specified key exists in the defined dictionary with python
Behavior when multiple servers are specified in nameservers of dnspython
How to turn the for statement when there are multiple values for one key in the dictionary
The story when different distributions are specified for the same parameter in Optuna
Behavior when returning in the with block
Display Python 3 in the browser with MAMP
Process multiple lists with for in Python
How to write a string when there are multiple lines in python
Notify using Notification Center when the execution environment is macOS in Python
[Python] Read the specified line in the file
What I did when I got stuck in the time limit with lambda python
When using PyQtGraph with Python Pyside, pay attention to the order of import
Compare the sum of each element in two lists with the specified value in Python
Character strings placed in GCS with python are garbled when viewed with a browser
[Python] Get the files in a folder with Python
Load the network modeled with Rhinoceros in Python ③
Prepare the execution environment of Python3 with Docker
Check if the characters are similar in Python
[Automation] Extract the table in PDF with Python
Precautions when dealing with control structures in Python 2.6
Character encoding when dealing with files in Python 3
Load the network modeled with Rhinoceros in Python ②
Multiple graphs are displayed in one window (python)
[Python] Dealing with multiple call errors in ray.init
Sort list elements in a specified order in Python
Load the network modeled with Rhinoceros in Python ①
What are you using when testing with Python?
Sort tuple list in Python by specifying the ascending / descending order of multiple keys
Python --If statement judgment behavior under multiple conditions (even though the order is different)
When will the default arguments be bound in python? When variables are bound in closure lazy evaluation.
Initial settings when using the foursquare API in python
[Python] Get the numbers in the graph image with OCR
When there are multiple Selenium SeleniumBasic classes (Python VBA)
Precautions when dealing with ROS MultiArray types in Python
Crawl the URL contained in the twitter tweet with python
Mailbox selection when retrieving Gmail with imaplib in python
Convert the image in .zip to PDF with Python
Get the result in dict format with Python psycopg2
Write letters in the card illustration with OpenCV python
Reproduce the execution example of Chapter 4 of Hajipata in Python
Japanese output when dealing with python in visual studio
[Python] How to output the list values in order
Reproduce the execution example of Chapter 5 of Hajipata in Python
Using the LibreOffice app in Python (1) Where are the macros?
Rewrite field order nodes in SPSS Modeler with Python.
For those who are in trouble because NFC is read infinitely when reading NFC with Python
A story that went missing when I specified a path starting with a tilde (~) in python open
Natural order in python
When the variable name conflicts with the Devaga command in pdb
[Python] Open the csv file in the folder specified by pandas
Calculate the square root of 2 in millions of digits with python
Solution when the image cannot be displayed with tkinter [python]
Master the type in Python? (When should type check be done)
How to define multiple variables in a python for statement
Behavior in each language when coroutines are reused with for
Process the files in the folder in order with a shell script
[Homology] Count the number of holes in data with Python
Solve the Japanese problem when using the CSV module in Python.