class – How do __enter__ and __exit__ work in Python decorator classes?

class – How do __enter__ and __exit__ work in Python decorator classes?

the __exit__() method should accept information about exceptions that come up in the with: block. See here.

The following modification of your code works:

def __exit__(self, exc_type, exc_value, tb):
    if exc_type is not None:
        traceback.print_exception(exc_type, exc_value, tb)
        # return False # uncomment to pass exception through

    return True

Then you can try raising an exception in one of your with: blocks and itll be caught in __exit__().

The reason why you are getting that error is becuase __exit__() takes 3 arguments along with self. These are:

  1. exception_type
  2. exception_value
  3. traceback

You can define __exit__() method two ways:

def __exit__(self, exception_type, exception_value, traceback):


def __exit__(self, *args, **kwargs):

with statement supports the concept of a runtime context defined by a context manager implemented using __enter__() & __exit__() method pair. Please visit this link for detailed info.

__enter__() method will enter the runtime context and return either this object or another object related to the runtime context.

__exit__() method will exit the runtime context and return a Boolean flag indicating if any exception that occurred should be suppressed. The values of these arguments contain information regarding the thrown exception. If the values equal to None means no exception was thrown.

class – How do __enter__ and __exit__ work in Python decorator classes?

Leave a Reply

Your email address will not be published. Required fields are marked *