简体   繁体   中英

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

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.

What you're doing looks totally fine and Pythonic. Although, the contextlib standard library already has something similar, but you'll have to rename your Close methods to close .

import contextlib
with contextlib.closing(thing):
    print thing

I would recommend using this instead. After all, the recommended naming convention for Python methods is all_lowercase_with_underscores .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM