LoginSignup
6
7

More than 5 years have passed since last update.

with構文を簡単に作る

Last updated at Posted at 2014-07-31

背景

  • 「準備→作業→後始末」、準備と後始末は共通の手続き、作業はいろいろ。
  • try ... finallyは何となく見栄えがよくないような?
  • openやfabricのcdのような、with構文を作りたい。
  • __enter__とか、__exit__とか、難しそう・・・。
  • rubyのブロック付きメソッドとyieldのような感じで簡単つくれないかなぁ。

解法

contextmanagerデコレータを使うことで、比較的簡単に、また、rubyのブロックに近い感覚で書くことができる。

参考リンクのままの例だが

from contextlib import contextmanager

@contextmanager
def tag(name):
    print "<%s>" % name
    yield
    print "</%s>" % name

>>> with tag("h1"):
...    print "foo"
...
<h1>
foo
</h1>

こんな感じです。

詳細

  • withブロックから抜ける手段が無い。

参考リンク

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