Python REPL: issuing commands in advance to execute after block

This is a bit of an odd question; it came up in the context of a tool that exposes a Python API, which we spend a lot of time querying interactively from the REPL. The particular idiom causing issues is something like this:

for var in slow_generator_of_giant_list():
    stats = update(stats, var)
print stats

To enter this at the REPL, I can type this:

>>> for var in slow_generator_of_giant_list():
...    stats = update(stats, var)

If I now attempt to type the print, I get a syntax error due to improper indentation. (Or else I put the print inside the loop and do it on every iteration.)

But if I hit enter to go to the next line, the loop runs immediately, and I have to wait for it to finish, or type the print command in the face of possible output coming at me, etc.

Obviously I can define a function containing the above, and it might be worth saving into a file anyway, but in the general case we're constructing these on the fly, and it would be nice to have a way to "schedule" a command to run after the end of a loop from the REPL. In a language with block delimiters, I could of course put it after the ending delimiter (and any necessary statement separator). But my coworkers and I were stumped trying to do something similar here.

Is there perhaps an ugly abuse of Pythonic syntax that will do the trick that my coworkers and I couldn't think of? Or a recommended way to avoid the problem while still making it easy to throw together ad hoc interactive queries?

Thanks for any pointers.


Not beautiful, but this should work:

>>> mygen = slow_generator_of_giant_list()
>>> try:
...     while True: stats = update(stats,
... except StopIteration:
...     print stats

Need Your Help