staggart
staggart

Reputation: 368

should __exit__ superclass method be called from subclass in python

I am not sure why this even dawned on me but if I have a context manager compliant class that is a subclass of another context manager class as shown below. I have shown the "typical" model where __exit__ calls close(). My question is: should bar.__exit__() explicitly call super(bar,self).__exit__(args) or should bar's close() call foo's close or??? What is the recommend model here in this case?

class foo(object):
    def __enter__(self):
        pass
    def __exit__(self,*exc_info):
        self.close()
        return False
    def close(self):
      pass
class bar(foo):
    def __enter__(self):
        pass
    def __exit__(self,*exc_info):
        self.close()
        return False
    def close(self):
        super(bar,self).close()   # is this the recommend model?

Thanks.

Upvotes: 4

Views: 2935

Answers (1)

As it might be impossible to know in general case what the __exit__ method does, I'd call it with the same arguments; if I want to throw an exception, then give it that exception instead in its __exit__, and then raise it after the exception has returned... but all in all this sounds a bit hacky; the better way could be so that you either do not override the __exit__ and just override the close method (relying on the fact that it gets called anyway by the superclass); or chain these 2 context managers if they really do something different.

Upvotes: 2

Related Questions