The correct way to handle exceptions in the Python2.7 context manager class

I have several context managers for the project I'm working on. He is about to send, and I am faced with what I'm starting to panic about.

I got the impression that you should not reraise the exceptions passed as arguments to the __exit__ method of the context manager class. However, I was preparing some tests, and it seemed that the context manager was suppressing the exception that throws it. When I changed the __exit__ methods to look like this:

def __exit__(self, type_, value, trace):
    if trace is not None:
        print('ERROR IN TRACEBACK: ' + str(value))
        # PYTHON 2.7 RAISE SYNTAX:
        raise type_, value, trace

the errors seemed to go right.

My question is: how to handle exceptions in the __exit__ method correctly if type_, value and trace are not None? Is it wrong to raise (re-raise?) Such an exception? So should I do this?

The error I encountered may be caused by something else. Usually I went through and thoroughly tested all this, but my time seems very limited at the moment. I hope someone can explain the correct implementation of this function and

In the end: Can I safely leave the raise_ method, value, trace in my __exit__ context manager?

+4
source share
1 answer

The return value of the method __exit__should indicate the need to re-raise or exclude any exception (for documents )

contextmanager.__exit__(exc_type, exc_val, exc_tb)

, , . with , . : None.

, __exit__ - False -y, , .

, docs explicilty state :

- , , , . (, contextlib.nested), , __exit__() .

+7

Source: https://habr.com/ru/post/1547980/


All Articles