Search code examples
pythonmatplotlibjupyter-notebookpython-importpython-module

What is the correct way to import modules when I'm writing my own module in python?


I've searched for similar questions, but what I've found doesn't work for me.
I'm writing the report of my analysis in a jupyter notebook (let's say main.ipynb). I want to import an external functions.py file with some functions that I use to plot some results. To be precise, my working directory has the following structure:
-main.ipynb
-utils
----functions.py
---- other files...

The functions.py file is something like this:

import matplotlib.pyplot as plt


def myPlot():
    plt.figure()
    plt.plot([0,1],[0,1])
    plt.show()
    ....

and the first cell of the notebook is this:

import matplotlib.pyplot as plt
from utils.functions import *

myPlot()

When I run the notebook I get this error: NameError: name 'plt' is not defined, although I have defined plt in both files (even if I think I really shouldn't need it in the main.ipynb).

S0, what is the correct way to import a package (matplotlib.pyplot in this case) in an external file? What am I doing wrong?


Solution

  • I've found the flaw in my code and I think it's worth sharing, so here I am.
    Maybe for beginners using jupyter notebook (as me) this could be tricky to detect: once you've run the cell with the import statement, it doesn't matter if you edit your file functions.py and re-run that cell. The kernel has already imported a file with that exact same name, so it won't notice the difference even if you've made changes.

    The solution I found (and I think is the only one) is to restart the kernel every time you change the functions.py file.