Home > Blockchain >  How to make VSCode don't cache imported methods?
How to make VSCode don't cache imported methods?

Time:04-08

I'm using imported methods from a .py file in a jupyter notebook and I wish to edit the .py file and use the updated function in the notebook. Currently, when I change a function or class in the .py file I have to close this file in VSCode and restart the notebook kernel to use the methods with the change I just made in the .py file, as if VSCode uses a cached version of the .py file if I don't restart the jupyter kernel. Is there anyway to change this setting? I used to work like this in PyCharm and it worked fine.

CodePudding user response:

In jupyter notebook, because the way of parsing files is based on JSON, the file format saved by default is not .py is .ipynb。 And .ipynb files cannot be simply imported to .py or .ipynb file, which brings great inconvenience to the development. Because in Jupiter notebook, it must be in the default .ipynb can support a series of features, such as automatic completion, console waiting, and so on .py files can only be modified through a text editor, which is very inconvenient.

Because .ipynb can import .py module, so one of the solutions is to convert the .ipynb module to .py file. Create a new cell at the end of the .ipynb file. Adding the following codes:

    try:

!jupyter nbconvert --to python file_name.ipynb
    except:

    pass

# file_ name.ipynb is the file name of the current module

Then a file with the same name will be generated in the current .py file, this module can be used in other .ipynb.

CodePudding user response:

You need to enable the auto reload magic in IPython. Try running the following before your code:

from IPython import get_ipython
ip = get_ipython()
ip.magic("reload_ext autoreload")  # these will enable module autoreloading
ip.magic("autoreload 2")
  • Related