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.