withステートメント
- ファイル閉じる
- ロック開放
- 補助処理の追加
- 特殊環境中実行の保守コード
などの時に使うといいらしい。結構べんりかも。
withステートメントを使ってtry...finallyと似たような動きできる。
# Expert Python Programming より引用 class Context(object): def __enter__(self): print 'Enter context' def __exit__(self, exception_type, exception_value, exception_traceback): print 'leaving the zone' if exception_type is None: print 'with no error' else: print 'with an error (%s)' % exception_value with Context(): print 'start1' #Enter context #start1 #leaving the zone #with no error with Context(): print 'start2' raise TypeError('i am the bug') #Enter context #start2 #leaving the zone #with an error (i am the bug)