# Code re-use in cookbooks

**URL:** <https://discourse.pangeo.io/t/code-re-use-in-cookbooks/4405>\
**Category:** Project Pythia\
**Created:** [August 2, 2024, 7:00pm UTC](https://discourse.pangeo.io/t/code-re-use-in-cookbooks/4405 "2024-08-02T19:00:12Z")\
**Posts on this page:** 7\
**Page:** 1

<div class="post-metadata">

**Author:** ![clyne](https://yyz2.discourse-cdn.com/flex030/user_avatar/discourse.pangeo.io/clyne/32/748_2.png) [@clyne](https://discourse.pangeo.io/u/clyne)\
**Post date:** [August 2, 2024, 7:00pm UTC](https://discourse.pangeo.io/t/code-re-use-in-cookbooks/4405/1 "2024-08-02T19:00:12Z")

</div>

How should code re-use be handled in cookbooks? In particular, let’s say I have a function that is used in multiple chapters AND the code is something that I want to illustrate to the reader. Ideally I’d like to define and show the functions only once (e.g. in the introduction), but then call it from other notebooks in the collection. Current practices seems to be to re-define the function in every chapter where it is used, which is a maintenance headache and results in a lot of clutter. Putting the function in a local module might be one option, but then how does the reader view it? Also, it puts up another barrier for cookbook creators in that they have to know how to create Python modules.

Any thoughts?

---

<div class="post-metadata">

**Author:** ![kafitzgerald](https://yyz2.discourse-cdn.com/flex030/user_avatar/discourse.pangeo.io/kafitzgerald/32/2223_2.png) [@kafitzgerald](https://discourse.pangeo.io/u/kafitzgerald)\
**Post date:** [August 2, 2024, 8:04pm UTC](https://discourse.pangeo.io/t/code-re-use-in-cookbooks/4405/2 "2024-08-02T20:04:14Z")

</div>

We use the `literalinclude` directive ([related discussion](https://github.com/orgs/executablebooks/discussions/818) and [example in the sphinx-book-theme docs](https://sphinx-book-theme.readthedocs.io/en/stable/reference/kitchen-sink/blocks.html#id1)) to do something like this on some GeoCAT projects (i.e. show a separate script in a notebook).

If it’s something getting a lot of reuse though, a more robust home than a local module might make sense (e.g. a package somewhere). Not sure if that’s practical or makes sense for the cases you’re talking about.

---

<div class="post-metadata">

**Author:** ![kmpaul](https://yyz2.discourse-cdn.com/flex030/user_avatar/discourse.pangeo.io/kmpaul/32/139_2.png) [@kmpaul](https://discourse.pangeo.io/u/kmpaul)\
**Post date:** [August 2, 2024, 9:54pm UTC](https://discourse.pangeo.io/t/code-re-use-in-cookbooks/4405/3 "2024-08-02T21:54:14Z")

</div>

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:

```auto
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:

```auto
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:

```auto
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.

---

<div class="post-metadata">

**Author:** ![kmpaul](https://yyz2.discourse-cdn.com/flex030/user_avatar/discourse.pangeo.io/kmpaul/32/139_2.png) [@kmpaul](https://discourse.pangeo.io/u/kmpaul)\
**Post date:** [August 2, 2024, 10:01pm UTC](https://discourse.pangeo.io/t/code-re-use-in-cookbooks/4405/4 "2024-08-02T22:01:26Z")

</div>

Here’s an example of the above approach.

I created a module called `mymod.py` with the contents:

```auto
def myfunc(x):
    """
    This is my function
    """

    # Just return 1
    return 1

```

And another module called `display_source.py` with the contents:

```auto
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)

```

Then, in my notebook I did:

```auto
from mymod import myfunc
from display_source import display_source

display_source(myfunc)

```

The output is (screenshot):

![image](https://canada1.discourse-cdn.com/flex030/uploads/pangeo/original/2X/e/e9fe01e35e193aa2cd4357b1328f8cc382bdbb2f.png)

---

<div class="post-metadata">

**Author:** ![gtrantham](https://yyz2.discourse-cdn.com/flex030/user_avatar/discourse.pangeo.io/gtrantham/32/1926_2.png) [@gtrantham](https://discourse.pangeo.io/u/gtrantham)\
**Post date:** [August 4, 2024, 2:20am UTC](https://discourse.pangeo.io/t/code-re-use-in-cookbooks/4405/5 "2024-08-04T02:20:08Z")

</div>

@clyne ,

Have a look at the `%run` jupyter magic. It might do what you want. This is not pythia-specific, but rather a bog-standard notebook capability that fits in jupyter-book projects.

I’ve used this successfully on jupyter-book builds where one notebook in the intro explains some process and builds a particular utility function. Other notebooks `%run` this intro notebook, and that puts the function into the execution environment. If you want to get really fancy, tag the `%run` cell with one of the [tags](https://jupyterbook.org/en/stable/interactive/hiding.html#hide-code-cell-content) which direct jupyter-book’s behavior to show (or not) that cell. I’ve also used this technique to include utility functions defined in an appendix to the book (instead of its intro).

There are also good arguments against using `%run` in this way. You need to be careful with what you include in the re-used notebook. It will be run in its entirety, so watch out for side effects or long execution times. You can also get into circular or recursive execution if you start running things without a well-defined structure for what runs what. But for the simple use case you describe–where exactly one small notebook contains code to be used by many other notebooks–it might be a good fit for you.

–gt

---

<div class="post-metadata">

**Author:** ![TomNicholas](https://yyz2.discourse-cdn.com/flex030/user_avatar/discourse.pangeo.io/tomnicholas/32/3189_2.png) [@TomNicholas](https://discourse.pangeo.io/u/TomNicholas)\
**Post date:** [August 4, 2024, 8:07pm UTC](https://discourse.pangeo.io/t/code-re-use-in-cookbooks/4405/6 "2024-08-04T20:07:22Z")

</div>

> [@kafitzgerald](#):
>
> If it’s something getting a lot of reuse though, a more robust home than a local module might make sense (e.g. a package somewhere).

I agree - IMO we should be trying as much as possible to identify commonly-repeated patterns and develop the package ecosystem so that such tasks become automated (or trivially quick).

---

<div class="post-metadata">

**Author:** ![clyne](https://yyz2.discourse-cdn.com/flex030/user_avatar/discourse.pangeo.io/clyne/32/748_2.png) [@clyne](https://discourse.pangeo.io/u/clyne)\
**Post date:** [August 5, 2024, 5:48pm UTC](https://discourse.pangeo.io/t/code-re-use-in-cookbooks/4405/7 "2024-08-05T17:48:46Z")

</div>

Thanks for all of the suggestions. I think are some good options here for dealing with cookbook utility functions that are re-used within a cookbook, but probably aren’t generalizable for broader use.
