Code re-use in cookbooks

If you want to use the local module approach, you can display selected source code for specific objects with the builtin Python inspect module, like so:

import inspect

def myfunc(x):
    """Docstring"""
    # Comment
    return x

print(inspect.getsource(myfunc))

This will literally print the source for the myfunc function as a string. But it won’t be pretty, because what you probably really want is to syntax-highlight that string so it looks nice in a Jupyter Notebook.

For that, you can use the Python pygments package. Combined with the builtin Jupyter core methods for displaying HTML, you can write a fairly simple display_source function like so:

from IPython.display import display, HTML
from pygments import highlight
from pygments.lexers import PythonLexer
from pygments.formatters import HtmlFormatter

def display_source(obj, color=True):
    obj_src = inspect.getsource(obj)
    if color:
        display(HTML(highlight(obj_src, PythonLexer(), HtmlFormatter())))
    else:
        print(obj_src)

This will use pygments to syntax-highlight the source string returned by inspect.getsource(obj) and return it as HTML, which Jupyter’s display(HTML(...)) function combination can display for you as pretty syntax-highlighted Python source.

You can package the display_source function in another local module in your cookbooks. Then when you want to show people the source for a given function, you simply have to:

from display_source import display_source
from mymodule import myfunc

display_source(myfunc)

It’s a bit more involved, but perhaps not so involved that it creates a barrier to usage.

Just an idea.