I have a pet project which I started as a Jupyter notebook. So far, I put all the Python code in the notebook.
At the start everything was fine. But over time the code I wrote in the notebook became more and more complex. Now it is close to unmanagenable: When I find an error, I need
I want to separate the code in two parts:
Let's assume that the notebook runs on my local machine (Windows 7; Jupyter runs in Anaconda) and the Python files are also stored locally.
What are good ways to use code from IPython files such that I can modify this code frequently and fast?
By "frequently and fast" I mean "with as little steps as possible that are necessary to propagate changes from Python files to the notebook". The ideal solution would be something where I change one of the Python files, run one command, and then the changes are available in the Jupyter notebook. Or, to use an older analogy, I want it to be like PHP -- you change the code often and immediately see the results of your changes.
Update 1: I tried to use the solution with %load TestClass.py
in a cell.
The problem is that the cell contents is not updated, if the file changes.
Example:
Let's say I put the text
class TestClass:
def __init__(self):
print("TestClass constructor")
into TestClass.py
. Then I create a cell in Jupyter notebook with %load TestClass.py
. When I execute that cell, the code from TestClass.py
is imported and the line %load TestClass.py
gets commented out.
Now I change TestClass.py
to
class TestClass:
def __init__(self):
print("TestClass constructor")
print("change")
When I execute the cell, its contents has not changed.
Inside the Notebook. When you open a new Jupyter notebook, you'll notice that it contains a cell. Cells are how notebooks are structured and are the areas where you write your code. To run a piece of code, click on the cell to select it, then press SHIFT+ENTER or press the play button in the toolbar above.
Sounds like the autoload extension of IPython is exactly what you need. Simply plug
%load_ext autoreload
%autoreload 2
in one of the first cells of your Jupyter notebook and imported python modules are automatically reloaded on change. You also can do changes to installed python packages, provided you have installed them editable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With