我经常发现自己使用的第三方库(包和模块)缺乏足够的文档。因此,研究源代码变得必不可少,但也可能是一项有些乏味的任务。我(我猜大家)使用 dir()
和 help()
函数开始,最近我开始使用 inspect
模块。我想知道您使用什么“方法”来深入研究记录不当的代码,以及如何提高这样做的效率。非常感谢帮助。
最佳答案
我找到了 IPython对于这种任务来说是必不可少的。 ?
(show docstring) 和 ??
(show source) 魔术命令,再加上 IPython 出色的完成系统和事件对象自省(introspection),对我来说真的很重要。
示例 session :
In [1]: import sphinx.writers <TAB>
# see available modules and packages - narrow down
In [1]: import shpinx.writers.manpage as manpage
In [2]: manpage.<TAB>
# list and complete on the module's contents
In [3]: manpage.Writer?
# nicely formatted docstring follows
In [4]: manpage.Writer??
# nicely formatted source code follows
In [5]: %edit manpage
# open module in editor
# it really helps if you use something like ctags at this point
In [6]: %edit manpage.Writer
# open module in editor - jump to class Writer
不幸的是,并非所有代码都可以通过这种方式进行检查。想想在模块中做事 而不将它们包装在 if __name__ == '__main__'
中的项目或严重依赖魔法的项目(想到 sh)。
关于Python:实用的内省(introspection),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12508621/