How to create a context manager with a loop inside?

I need something like this:

from contextlib import contextmanager @contextmanager def loop(seq): for i in seq: try: do_setup(i) yield # with body executes here do_cleanup(i) except CustomError as e: print(e) with loop([1,2,3]): do_something_else() do_whatever() 

But the contextmanager does not work, because it expects the generator to give exactly once.

The reason I want this is because I basically want to make my own for the loop. I have a modified IPython that is used to control test equipment. This is obviously a complete Python REPL, but most of the time the user simply calls the predefined functions (similar to the Bash prompt) and the user does not have to be a programmer or familiar with Python. There should be a way to iterate over some arbitrary code with setting / clearing and handling exceptions for each iteration, and it should be about as easy to type as indicated above using the instructions.

+5
source share
1 answer

I think the generator works better here:

 def loop(seq): for i in seq: try: print('before') yield i # with body executes here print('after') except CustomError as e: print(e) for i in loop([1,2,3]): print(i) print('code') 

will give:

 before 1 code after before 2 code after before 3 code after 

Python enters and exits the with block only once, so you cannot enter logical I / O steps that will be repeated.

+7
source

All Articles