3

In the file mylibrary.py I have the function

def myfunc(a,b):
    return a+b

and in a Jupyter notebook I run

import mylibrary
mylibrary.myfunc(1,2)

and the output is 3 as expected.

However, when I update the the file mylibrary.py so that its contents are

def myfunc(a):
    return a+1

and run in Jupyter

import mylibrary
mylibrary.myfunc(1,2)

the output is an error:

TypeError: myfunc() missing 1 required positional argument: 'b'

Apparently Jupyter is still using the old version of mylibrary.py. The error persists if I delete the cache created for mylibrary.py after I try to import it.

Why is this happening, and how can I correct it? (An obvious workaround would be to define myfunc in the Jupyter notebook instead of having it separate, which for now I will do. However, that works around the problem instead of actually fixing it, so that I still don't understand what went wrong and I may fall into a pitfall later as a result. Therefore, I think it's worthwhile to figure out what is going wrong.)

BGreen
  • 370
  • 3
  • 17
  • 1
    does this help? [Reloading submodules in IPython](https://stackoverflow.com/questions/5364050/reloading-submodules-in-ipython) – Thomas Dec 21 '20 at 23:21
  • Unfortunately, no; I tried running `%load_ext autoreload` followed by `%autoreload 2` but still get the same error. – BGreen Dec 22 '20 at 00:19
  • I think that you should run `%load_ext autoreload` and `%autoreload 2` prior to importing the file for the first time in a notebook. – krassowski Jan 13 '21 at 12:23
  • Thanks for the suggestion. I just tried placing both before and after the import and in both cases the old version was still used. For what it's worth, I've just found that running `import importlib` then `import mylibrary` then `mylibrary = importlib.reload(mylibrary)` works, although it's clunky. – BGreen Jan 14 '21 at 14:57

0 Answers0