Reputation: 187
I have a file called "Notebook.ipynb". I want to import my own module into it patterns.py. Let's say in patterns.py I have a variable a=1
. If I print it in Jupyter after importing it, I expect to get 1. But if I change the value of the variable to patterns.py Jupyter will continue to think that the variable a
is equal to one. At the same time, of course, I restart the cell in which the variable is imported from patterns.py
What do I need to do to make Jupyter understand that the value of the variable has changed?
Upvotes: 11
Views: 11222
Reputation: 312
Just in addition to @ilia post: Let's say the module's name is main.py That's the code I put in the Jupiter's notebook cell, just before calling functions from the main module
import importlib
imported_module = importlib.import_module("main")
importlib.reload(imported_module)
from main import *
Upvotes: 2
Reputation: 565
There's actually a nifty IPython extension for this called autoreload. This answer shows how to use it in an IPython shell, but you can do the same in a Jupyter notebook. Just add:
%load_ext autoreload
%autoreload 2
before you import the module whose changes you want to have tracked, and it'll be re-imported before every cell you execute.
Upvotes: 11
Reputation: 640
Suppose we have a file at folder_name/filename.py
and call it in some .ipynb
def some_func():
print("test")
which was modified like this
def some_func():
print("test2")
In this case, second call of the following code in .ipynb
import folder_name.filename as module_name
module_name.some_func()
returns test
To update the function, you need to reload the module:
importlib.reload(module_name)
# you can reload "folder_name.filename" if you do not use molude name alias
module_name.some_func()
This code will return test2
Don't forget to import importlib
before you run reload
Upvotes: 8
Reputation: 121
This has happened to me.
You need to restart the python kernel so jupyter can read the new state of the python scripts located in the working directory.
Then the variable a
should print the new assigned value.
Upvotes: 4