object.enable() anti-pattern

Christian Heimes christian at python.org
Wed May 8 05:51:47 EDT 2013


Am 08.05.2013 10:52, schrieb Steven D'Aprano:
> Basically, any time you have two steps required for using an object, e.g. 
> like this:
> 
> obj = someobject(arg1, arg2)
> obj.enable()
> 
> you should move the make-it-work functionality out of the enable method 
> and into __init__ so that creating the object creates it in a state ready 
> to work.

In general I agree that an object.enable() function is ugly. ;)

But it's not necessarily the best solution for all problems. If the
resource needs some kind of cleanup, the context api (__enter__() /
__exit__()) is perfectly fine way to enable and disable the object.

For example:

class MyFile:
    def __init__(self, filename):
        self.filename = filename
    def __enter__(self):
        self.open()
        return self
    def __exit__(self, exc_type, exc_val, exc_tb):
        self.close()

I suggest that you mention the context API in your blog post, too.

Christian




More information about the Python-list mailing list