Import new code into Jupyter Lab

喜你入骨 提交于 2020-01-05 07:09:32

问题


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?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/49326354/import-new-code-into-jupyter-lab

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!