Import new code into Jupyter Lab

2019-07-23 11:05发布

I am importing some python functions into a Jupyter Lab notebook and then using them within the notebook. But I am going back and forth between making alterations to the functions and then rerunning them in the Jupyter Lab notebook. The only way I have found to get Jupyter Lab to use the updated code is to restart the kernel and then rerun everything. While this works fine, it is a bit cumbersome because I need to run everything in the notebook again.

Is there a better way to allow Jupyter Lab to see the new changes in an imported function while still retaining all previously set variables?

2条回答
Evening l夕情丶
2楼-- · 2019-07-23 11:55

You can reload the module you are importing you function from.

Suppose in your notebook you have:

from mymodule import myfunction
myfunction()
# execute old version of myfunction

Then you go and change myfunction in mymodule.py. Reload the module:

import importlib
importlib.reload(mymodule)

If you call myfunction() now, the new version will be executed.

查看更多
ゆ 、 Hurt°
3楼-- · 2019-07-23 11:58

You can also use the reload magic by placing this in your notebook. It will automatically reload code.

%reload_ext autoreload
%autoreload 2

The only time this may cause confusion is, if you instantiated an object, change the code and then wonder, why the already instantiated object does not have the new functions. Besides this case, it works well.

查看更多
登录 后发表回答