I'm a noob with Python, but I've written an auto-close function like this..
@contextmanager
def AutoClose(obj):
try:
yield obj
finally:
obj.Close()
I have three classes that have a Close() method that this function can be used with. Is this the most Pythonic solution? Should I be doing something in the classes themselves instead?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With