1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Pythonのwith文に複数のcontext managerを指定した場合の実行順序

Posted at

PythonのLanguage Referenceによると、withには複数のcontext managerを指定できます。

Language_Referenceより抜粋
with A() as a, B() as b:
    SUITE

これはネストしたwith文と同等とのこと。

Language_Referenceより抜粋
with A() as a:
    with B() as b:
        SUITE

となると、 __exit__() が呼ばれる順序は書いた順の逆(B→A)になるはずです。

実際にサンプルを書いて確かめました。

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')
実行結果
$ python my_context_manager.py
A enter
B enter
do something
B exit
A exit

確かに、逆順になっています。

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?