基本的な使い方
ファイルを開いて読み込む処理が典型的かな。今まではこうしていた:
1 2 3 |
f = open('data.txt', 'r') print f.read() f.close() |
with 構文を使うとこう書ける:
1 2 |
with open('data.txt', 'r') as f: print f.read() |
開いたファイルは、ブロックを抜けるときに自動で閉じてくれる。
withに対応したクラス
with 構文に書けるクラスはファイルだけじゃない。__enter__
と __exit__
の2つのメソッドを持ったクラス(のインスタンス)なら何でもいい。__enter__
はブロックに入るときに、__exit__
はブロックを抜けるときに呼ばれる。
ちょっと試してみよう。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
class Test(): def __init__(self, hoge): print 'init' self.hoge = hoge def print_hoge(self): print self.hoge def __enter__(self): print 'enter' return self def __exit__(self, type, value, traceback): print 'exit' with Test('hoge') as t: t.print_hoge() |
実行結果:
takatoh@apostrophe $ python test_with.py init enter hoge exit
ブロックの中を実行する前に __enter__
が、あとに __exit__
が呼ばれているのがわかる。
as t:
の部分の t
には、__enter__
の返り値が代入されるので、self
を返している。
ともあれ、1行短くなって見やすくなる。これからはこうやって書くようにしよう。