0

I have a script that I am in the process of debugging. I've imported it using:

import foo

Then I update foo. After I do "import foo" again, nothing is changed. How do I update it without needing to exist the interpreter and reenter? Furthermore, if there are other packages that depend on it, how do I update them to use the newest version?

martineau
  • 119,623
  • 25
  • 170
  • 301
JobHunter69
  • 1,706
  • 5
  • 25
  • 49

1 Answers1

1

Use importlib.reload(). This used to be a builtin (in Python 2), but it doesn't clean up everything. This was considered too confusing and it was moved to importlib for advanced users. Read the documentation carefully to understand why.

>>> import foo
>>> from importlib import reload
>>> # do stuff
>>> reload(foo)

Modules in Python are cached in the sys.modules dict. They're only loaded from source on the first import. If you delete it there, you can get a similar effect.

The main difference between these two approaches is that reload() keeps the same module __dict__ object (its globals), while just deleting it from sys.modules wouldn't. Normally a reload will overwrite these globals with the new definitions if you modify the source. But if you remove a definition in the source, the old version will still be there after a reload. You can actually use this to your advantage in some cases: if you want a resource (like a network connection) to persist over reloads, you can write its initialization to skip the step if the global is already defined.

gilch
  • 10,813
  • 1
  • 23
  • 28