问题
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