how to run a jupyter notebook macro in a for loop

Viewed 448

I defined a macro inc in Jupyter Notebook. I can run a macro from another cell. However, the macro cannot be run in the for loop.

[1]

x = 0

[2]

x += 1

[3]

%macro inc 2

[4]

inc

[5]

x

outputs 2

[6]

for _ in range(10): inc

[7]

x

still outputs 2.

1 Answers

The best I came up with right now is using run_cell method

First you need to grab current interactive Ipython shell with get_ipython

Full example

ip = get_ipython()
for _ in range(5): ips.run_cell('inc')

This is not a solution that fully satisfies me but it maybe someone else will be able to add something better.


Note: Solution below works for older Ipython

try just running it as a callable:

for _ in range(10): inc()

Explanation

Ipython macros are instances of IPython.core.macro.Macro

Documentation states that it is just a simple objects storing chunk of history in a variable. And this is true.

In [20]: inc.__dict__
Out[20]: {'value': u'x += 1\n'}

You can also read:

Macro is just a callable that executes a string of IPython

Related