2

Jupyter Notebook has a %load magic that can load code into a cell of a notebook.

%load start.py

This line loads the content of start.py into the current cell. The magic is automatically commented out after execution.

# %load start.py
import numpy as np
import pandas as pd

Jupyter Notebook also has a %autoreload extension that can reload modules before executing code.

%load_ext autoreload
%autoreload 2
from utils import load_data

If there is a change in the load_data function, this extension can detect and auto-reload the new function before execution.

Is there a way to combine the functionality of these two? In other words, if the content of start.py change, how can I automatically detect the change and reload it into the cell before running code?

For example, if the content of start.py is now

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

I would like the cell to be reloaded to become:

# %load start.py
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
TQA
  • 267
  • 3
  • 12

1 Answers1

0

I think you're trying to mix things beyond the point they were intended.

If you want a hack, as you mention you could import a function from within start.py, then %autoreload will give you the functionality you want. You could then mix with this if you wanted to see the contents of the .py file:

with open("start.py") as f:
    print(f.read())

You could then easily copy and paste into a cell if needed.

cwalvoort
  • 1,851
  • 1
  • 18
  • 19