Is there an option to enable cellmagic on every cell?

It would be interesting if there was an option to decorate every single cell in a notebook with a cell magic without doing that manually.
That could be e.g. a function run_all_cells_with_magic('%%timeit')

That way, it would become easy to switch a cell magic on and off.

I found this question on Stack Overflow, but there is no answer that solves this challenge.

you could write a function run_all_cell_with_magics that configures IPython to prepend %%timeit to all your cells.

this doesn’t answer your about persistent magics. if you want to time every cell you install the GitHub - deshaw/jupyterlab-execute-time: A JupyterLab extension for displaying cell timings extension.

1 Like

I don’t know much about the IPython configuration.
Do you know where one can start implementing the prepending of cell magic in IPython?
Beside %%timeit, this could be very useful for other magics as well!

Thanks for the link to the JupyterLab extension, so far I’ve always used the built-in timer in the VS Code notebook environment.

in your IPython session, get_ipython is a function you can call to customize and configure your shell experience.

IPython input transformation docs have some examples for customization. in retrospect, this approach might have drawbacks if the magic calls IPython run cell machinery.

1 Like

Thanks for the docs link!

I’ve now managed to prepend a line like this:

def run_all_cell_with_magics(lines):
    new_lines = [] 
    new_lines.append("print('Hello Time') \n") #this works
    #new_lines.append("%%timeit \n") # this does not work

    for line in lines:
    return new_lines

ip = get_ipython()

and it actually prints “Hello Time” for every cell, as can be seen in this screenshot:

But that does not work for prepending %%timeit.
The docs also mentions that this is not possible:

Then IPython runs its own transformations to handle its special syntax, like %magics and !system commands. This part does not expose extension points.

Does that mean that this run_all_cell_with_magics function can only be implemented in IPython itself?

very cool that you got that working.

yea, you are going to get recursion when you try to run timeit in this manner. so make that work you’ll have to something fancy with a class or context manager.

magics are an IPython construct. so anything you implement with magics will be IPython specific.