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