Most pythonic solution is to define methods __enter__
and __exit__
methods in your class:
class Foo(object):
def __init__(self, filename):
self.filename = filename
def __enter__(self):
self.fd = open(self.filename)
def __exit__(self, exc_type, exc_value, traceback):
self.fd.close()
And using:
with Foo('/path/to/file') as foo:
# do something with foo
Methods __enter__
and __exit__
will be implicitly called when entering and leaving blocks with
. Also note that __exit__
allows you to catch exception which raised inside the block with
.
Function contextlib.closing
is typically used for those classes that do not explicitly define the methods __enter__
and __exit__
(but have a method close
). If you define your own classes, much better way is to define these methods.