Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python with statement, continue

I am developing a program in python and have reached a point I don't know how to solve. My intention is to use a with statement, an avoid the usage of try/except.

So far, my idea is being able to use the continue statement as it would be used inside the except. However, I don't seem to succeed.

Let's supposse this is my code:

def A(object):
    def __enter__:
        return self

    def __exit__:
        return True

with A():
    print "Ok"
    raise Exception("Excp")
    print "I want to get here"

print "Outside"

Reading the docs I have found out that by returning True inside the __exit__ method, I can prevent the exception from passing, as with the pass statement. However, this will immediately skip everything left to do in the with, which I'm trying to avoid as I want everything to be executed, even if an exception is raised.

So far I haven't been able to find a way to do this. Any advice would be appreciated. Thank you very much.


1 Answers

It's not possible.

The only two options are (a) let the exception propagate by returning a false-y value or (b) swallow the exception by returning True. There is no way to resume the code block from where the exception was thrown. Either way, your with block is over.

like image 84
John Kugelman Avatar answered Jul 11 '26 20:07

John Kugelman