I would like to invoke the code object again in the exit() method if it raises an exception (maybe several times, maybe with delay). I know it is very easy to do with a decorator, but my motivation is that sometimes I want to repeat just some fragment of code that I don't want to extract to a separate function and decorate it. I'm looking for something along these lines:
class again(object): def __enter__(self): pass def __exit__(self, exc_type, exc_val, exc_tb): if exc_type is not None: ???? # Invoke the code object again return True # eat exception
It would used like so:
x = 0with again(): print x x += 1 if x == 1: raise Exception('I hate 1')
and the expected output would be:
01
I could find a way to get hold of the code object. None of the context manager attributes seem to reference it (I guess it is not really needed, because it's job is just to do stuff before and after).
Is it possible to do it?