#๐Ÿ”’ Imported .py files don't update

16 messages ยท Page 1 of 1 (latest)

stuck crystal
#

I'm working in Jupyter Notebook. I have some .py files and a different .ipynb file where I'm importing them.

When I edit the .py file, I save it, I run again the box where I import the .py file and then I call it elsewhere in the .ipynb, it isn't the last saved version. Closing everything seems to work but that's very inefficient, is there any other way to force it to update?

twilit sparrowBOT
#

@stuck crystal

Python help channel opened

Remember to:

  • Ask your Python question, not if you can ask or if there's an expert who can help.
  • Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
  • Explain what you expect to happen and what actually happens.

:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.

royal widget
#

Imports are cached - if you import again Python thinks it's already do, and it is a no-op.

unkempt socket
royal widget
#

You could import sys and then del sys.modules['your-module-name'] then reimport it. Clumsy.

stuck crystal
#

I'll try both and see if it works

royal widget
#

Hmm there's importlib.reload. So:

import importlib # at the top of your notebook

then later:

reload(module_name)
#

!doc importlib.reload

twilit sparrowBOT
#

importlib.reload(module)```
Reload a previously imported *module*. The argument must be a module object, so it must have been successfully imported before. This is useful if you have edited the module source file using an external editor and want to try out the new version without leaving the Python interpreter. The return value is the module object (which can be different if re-importing causes a different object to be placed in [`sys.modules`](https://docs.python.org/3/library/sys.html#sys.modules)).

When [`reload()`](https://docs.python.org/3/library/importlib.html#importlib.reload) is executed:
royal widget
#

Reloading a module isn't quite the same as starting again. Consider:

import something
X = something.SomeClass(1)
.... later ...
reload(something)
Y = something.SomeClass(2)

X and Y are now not of the same class, because reloading something made a new class with the name SomeClass. There's a suite of little annoying sideeffects like this.

It is probably better to restart the kernel.

stuck crystal
#

Anyway, ideally I'd have to reload them just at the start of the notebook so things like those shouldn't happen

#

And it is working, so thanks you so much!

#

!close

twilit sparrowBOT
#
Python help channel closed with !close

This help channel has been closed. Feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.