Not sure if this is the right place, but I have an idea for a feature that I think would improve IPython / Jupyter.
Use Case:
Often when I copy paste code from a .py file into an IPython terminal it is code that exists in a loop. E.g.
loop_body_setup(data)
if condition(data, idx):
continue
loop_body_main_case(data)
but if I paste that into IPython, it fails to parse because it isn’t valid Python, and it gives a SyntaxError.
This also happens when the continue
is replaced by other control flow statements like break
or return _
.
But, it’s pretty close to valid Python, and if we have the variables “idx” and “data” in our IPython namespace, and we want to debug what happens in the body, we have to modify the code before we paste it into IPython. That’s kinda annoying. I’ve also found it encourages me to write roundabout code like
for idx in range(10):
loop_body_setup(data)
if condition(data, idx):
...
else:
loop_body_main_case(data)
to avoid syntax errors. But this code smells, and I think:
for idx in range(10):
loop_body_setup(data)
if condition(data, idx):
continue
loop_body_main_case(data)
is just better. But to use nicer code like this in IPython I need to piece-wise copy/paste it. Or, recently I’ve been replacing the continue
with a raise Exception
, which forshadows the proposed solution.
Proposal
Notice that for each control flow statement the body of the loop stops, so what if IPython is sneaky. What if when the user pastes in code like that and it catches a SyntaxError
, then it replaces the control flow statement with raise Exception('original control flow statement')
.
That will let the user modify the current IPython state just as a loop or function body would. If it hits the control flow statement, an error is raised and IPython’s current cell execution stops. The user can also notified of which control flow statement was hit by passing that information to the inserted Exception.
(As a side-note, this could be built into the Python language and its implementations, but it seems like IPython would be a good place to test its mettle.)
Thoughts?