Python:实用的内省(introspection)

标签 python introspection

我经常发现自己使用的第三方库(包和模块)缺乏足够的文档。因此,研究源代码变得必不可少,但也可能是一项有些乏味的任务。我(我猜大家)使用 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/

相关文章:

python - 初学者 - GUI 切换按钮

ruby-on-rails - rails : list accepted values of "validates :inclusion" field

ios - 在 Objective-C 中获取对象的属性名称作为字符串

python - 如何在 Python 中使用 Selenium 获取 h1 标签

python - 打印 Python 异常类型(在 Fabric 中引发)

python - 使用 python 修复格式错误的 XML

python - 如何在不等待的情况下调用异步函数?

java内省(introspection)查找类的成员

python - 在 Python 中查找原始异常的模块名称

.net - 在 VB .NET 中在运行时构造动态属性