無理やり with 対応
追記: contextlib.closing を使えばよかったのこと(^^;
GzipFile が標準ライブラリのくせに with に対応していなくてカッとなってやった. つか、close メソッド呼べばいいだけのクラスって多いと思うんだけど・・・.
import gzip from new import instancemethod def with_support(obj): obj.__enter__ = instancemethod(lambda self: self, obj, obj.__class__) obj.__exit__ = instancemethod(lambda self, type, value, traceback: self.close(), obj, obj.__class__) return obj with with_support(gzip.open('hello.txt.gz', 'w')) as f: f.write('Hello World!')
って、Python 2.6 のマニュアルに new は deprecated だから types を使えーと書いてあるではないか. じゃあ、ということで.
import gzip from types import MethodType def with_support(obj): obj.__enter__ = MethodType(lambda self: self, obj, obj.__class__) obj.__exit__ = MethodType(lambda self, type, value, traceback: self.close(), obj, obj.__class__) return obj with with_support(gzip.open('hello.txt.gz', 'w')) as f: f.write('Hello World!')