Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
509 views
in Technique[技术] by (71.8m points)

ipython - how to reload a Class in python shell?

If I import a module defining a class of the same name belonging to a package, it is imported as a Class, not a Module because of the __init__.py of the parent package. See different import results at different directories for details. In Python shell or ipython shell, if I do

from MyPak import MyMod

MyModule is always imported as Class thus I can not reload it (reload() works only for modules). Run

from MyPak import MyMod

again does not seem to update the Class definition. Could anyone suggest a way to update the class in python shell?

ps. without restarting the python interpreter.

pps. Just in case you have the code in hand and want to test it: I am actually talking about BioPython, and I am working on Bio.PDB.PDBParser. I have an ipython shell (v0.10) and edit PDBParser.py. Just got no way to reload it in ipython.

so here is what I did:

# start ipython v0.10
import Bio
from Bio.PDB import PDBParser
p = PDBParser()
s = p.get_structure()
# then I make changes,e.g. simply print some text, in PDBParser.py
del Bio
del PDBParser
del s
import Bio  # or reload(Bio) without deleting all the objects
from Bio.PDB import PDBParser
p = PDBParser()
s = p.get_structure() # expected output after change not seen :(

I could not see the printed text. The changes were not applied somehow.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...