Skip to content Skip to sidebar Skip to footer

Python Context Manager Not Passing Exceptions

Why does the following unit test fail, and how do I get my context manager to pass exceptions properly? I'm using python 3. test.py: class test(object): def __enter__(self):

Solution 1:

Your issue is here:

def__exit__(self, ex_type, ex_val, tb):
    return ex_type, ex_val, tb

The return value of __exit__ implies that you want to suppress those errors raised inside the context block.

Simply change it to return nothing or raise the error if any overflow error occurs. If any truthy value is returned, the context block suppresses the error. You need to return false. An example is as follows:

def__exit__(self, ex_type, ex_val, tb):
    if ex_type is OverflowError:
        returnFalsereturnTrue

Edit Martijn Pieters as always has a better explanation than me.

Post a Comment for "Python Context Manager Not Passing Exceptions"