AttributeError in "with" statement (3.2.2)

Steven D'Aprano steve+comp.lang.python at pearwood.info
Thu Dec 15 22:34:10 EST 2011


On Thu, 15 Dec 2011 05:35:55 -0800, Steve Howell wrote:

> For the special methods like __enter__ and __exit__, the tricky part
> isn't understanding what would happen once the methods were called; the
> tricky part is getting them to be called in the first place, if they
> were not declared inside the class or attached to the class.

If you *must* have per-instance special methods, my advice is to use a 
bit of scaffolding like this:

class Whatever:
    def __enter__(self, *args):
        try:
            enter = self.__dict__['__enter__']
        except KeyError:
            do_something_else()  # or just let the exception occur
        else:
            enter(*args)


Otherwise just live with the limitation that you can override all methods 
per-instance *except* dunders, and design your application accordingly.



-- 
Steven



More information about the Python-list mailing list