10
3

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

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

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?