Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the Pythonic way to write an auto-closing class?

Tags:

python

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?

like image 223
bluedog Avatar asked Aug 12 '13 06:08

bluedog


1 Answers

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.

like image 96
defuz Avatar answered Sep 27 '22 22:09

defuz