LoginSignup
9
3

More than 5 years have passed since last update.

withブロックの中でreturnした場合の挙動

Posted at

別に面白くもない確認。

with文のブロック内でreturnした場合にコンテキストマネージャの終了処理はちゃんと呼ばれるのか不安になって確かめた。

結論としては大丈夫。

withreturn.py
class Some(object):
    def add(self, x, y): 
        return x + y 

    def close(self):
        print "Closed"


from contextlib import closing
def foo(x):
    with closing(Some()) as some:
        return some.add(x, 10) 


print foo(16)
# Closed
#=> 26

このように終了処理が呼ばれる。

9
3
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
9
3