3

Problem: I like keeping ipython notebooks within jupyter clean and putting utility functions in outside file to keep, but calling them from the notebook as needed once written.

The issue is once I move the completed function to an outside file, I have to kill the kernel and re-run everything to import it!

I have tried doing the normal:

%load_ext autoreload
%autoreload 2

but it doesn't seem to work.

Any better suggestions?

lollercoaster
  • 15,969
  • 35
  • 115
  • 173
  • `autoreload` is also broken for me, though I remember it used to work about a year ago (I had a line `!ninja -C module_directory` / `%reload mymodule`. It is currently dysfunctional. – eudoxos Feb 27 '20 at 10:24
  • @lollercoaster How did my suggestion work out for you? – vestland Apr 30 '20 at 16:36

1 Answers1

1

You can use the magic function %run <filename> where you've got your utility functions defined.

I have had great use for this when I'm writing new utility functions and want to test and improve them in a jupyter notebook without restarting the whole thing each time. Check out chapter IPython Magic Commands by Jake VanderPlas for

Details:

I've got a file named utils.py in a folder named c:/jupytertest.

Utils.py:

import pandas as pd

def framer(df):
    df_out = df['parch'].to_frame()
    return(df_out)

And I've got the following in a jupyter notebook cell:

# standard imports
import os
import pandas as pd
os.chdir('C:/jupytertest/')

# run / reload utils
%run utils.py

# data
url = "https://raw.github.com/mattdelhey/kaggle-titanic/master/Data/train.csv"
titanic = pd.read_csv(url)

# test reloading of function from utils.py
values = framer(titanic)

print(values.tail(5))

Now every time I change df_out = df['parch'].to_frame() to name or any other column I know exists in the titanic dataset, the only thing I have to do to apply the up-dated function in jupyter is to save utils.py and re-run the cell in the notebook.

No kernel-restart in the notebook should be necessary.

Check out IPython Magic Commands in the Python Data science Handbook by Jake VanderPlas for even more details.

vestland
  • 55,229
  • 37
  • 187
  • 305