how to reload a Class in python shell?
I finally found the answer:
import MyPak
from MyPak import MyMod
after editing MyPak/MyMod.py
file, to reload the class MyMod
in the file MyMod.py
, one needs to
import sys
del sys.modules['MyPak.MyMod']
reload(MyPak)
from MyPak import MyMod
Caveats:
Executing
del MyPak
ordel MyMod
ordel MyPak.MyMod
does not solve the problem since it simply removes the name binding. Python only searchessys.modules
to see whether the modules had already been imported. Check out the discussion in the post module name in sys.modules and globals().When reloading MyPak, python tries to execute the line
from MyMod import MyMod
inMyPak/__init__.py
. However, it findsMyPak.MyMod
insys.modules
, thus it will NOT reloadMyMod
althoughMyPak/MyMod.py
has been updated. And you will find that no newMyPak/MyMod.pyc
is generated.
On Python 3 only, import the reload
function:
>>> from importlib import reload
On both Python 2.x, and 3.x, you can then simply call reload
on the module:
>>> import MyPak
>>> reload(MyPak)
>>> from MyPak import MyMod
However, instances of the old class will not be updated (there's simply no code that describes the update mechanism).