Cellmagic that converts code cell into a function

I had the idea for a cellmagic that converts a code cell into a function, it’s just a hacky proof of concept and I don’t know if this is actually useful.
As this new syntax allows to quickly create and remove functions from Jupyter cells without the need of code indentation, this could e.g. be used to accelerate the workflow of developing new functions.

Here is how it works:

%%magic_func foo
x = 34
x + 10 # RETURN

Note that the comment # RETURN is considered by the cellmagic.
The cellmagic will rewrite the whole code block as a function that is called foo() and returns x + 10.
In another cell, the function foo that can now be called like this:

from IPython import get_ipython
from IPython.core.magic import Magics, cell_magic, magics_class
from io import StringIO

class MyMagic(Magics):
    def magic_func(self, line, cell):
        new_codeblock = ""
        new_codeblock += f"def {line}():"
        new_codeblock += "\n"
        for codeline in StringIO(cell):
            new_codeblock += "\t"
            if "# RETURN" in codeline:
                new_codeblock += "return "
            new_codeblock += codeline


ipy = get_ipython()

This is a great idea for students and lazy programmers who don’t feel like formalizing their statements into a formal function.

Can this be added to the core Jupyter Magics library? Pardon my ignorance at the moment, but is there a “Jupyter Magics” package for this to find home? What is the process for accepting such enhancements into core package?

Thanks for your interest!

There are cell magics in the Ipython core library (built-in-magic-commands docs) but I think for %%magic_func magic this is not the right place.
In its current state, %%magic_func is quite hacky, and the defined functions are not understood by an ide (you won’t get auto-complete and there might be the warning “Function not defined” from the editor.)
Further, it’s not possible to phrase function arguments. That would be easy to implement:

  • Idea one would be to use the magic argument @magic_arguments.argument that can be used like %%magic_func --arg1 "x=3"
  • Idea two: similar to the x + 10 # RETURN syntax, function arguments could be annotated with ARGUMENT, e.g.
%%magic_func foo
x = 34 # ARGUMENT
x + 10 # RETURN

This could become a separate pypi project, e.g. community-cellmagic , similar to the way I’ve written jupyter_capture_output.

Some other cell magics that I have in mind and that could be part of that package:

A cell magic that runs certain lines multiple times:

x = 34
x + 10 # RUN2X
x * 2 # RUN10X

A cell magic that streams the code together with its output to communication platforms like discord or the Jupyter discourse:

import matplotlib.pyplot as plt
plt.plot([1,2], [10,20], c = "orange")