Reputation: 169
sorry, im sure this is asked a bunch, but i couldnt find it.
in myModule.py:
from myModule.subModule import myClass
i am working on myClass, and want to stay in my ipython session and test it. reload(myModule)
doesnt re-compile myClass.
how can i do this?
Upvotes: 4
Views: 1464
Reputation: 882191
You need to repeat your imports after reloading the "leafmost" submodule. E.g., given:
$ mkdir myModule
$ touch myModule/__init__.py
$ cat >myModule/subModule.py
class MyClass(object): kind='first'
and then
>>> from myModule.subModule import MyClass
>>> MyClass.kind
'first'
and in another terminal
$ cat >myModule/subModule.py
class MyClass(object): kind='second'
then...:
>>> import sys
>>> reload(sys.modules['myModule.subModule'])
<module 'myModule.subModule' from 'myModule/subModule.py'>
>>> from myModule.subModule import MyClass
>>> MyClass.kind
'second'
You need to go via sys.modules
as you don't otherwise have a reference to the submodule, and then you need to repeat the from
.
Life is much simpler if you accept the wise advice of always importing a module, never stuff from INSIDE the module, of course - e.g., the Python session would be (with a change to the submodule before the reload):
>>> from myModule import subModule as sm
>>> sm.MyClass.kind
'first'
>>> reload(sm)
<module 'myModule.subModule' from 'myModule/subModule.py'>
>>> sm.MyClass.kind
'second'
If you get into the habit of using qualified names such as sm.MyClass
instead of only the barename MyClass
, your life will be simpler in many respects (easier reloading is just one of them;-).
Upvotes: 2