【问题标题】:Python: practical introspectionPython:实用内省
【发布时间】:2012-09-20 08:18:00
【问题描述】:

我经常发现自己在使用缺乏足够文档的第三方库(包和模块)。因此,研究源代码变得必不可少,但也可能是一项有些乏味的任务。我(我猜大家)使用dir()help() 函数开始使用,最近我开始使用inspect 模块。我想知道您用来深入研究记录不良的代码的“方法”是什么,以及如何提高这样做的效率。非常感谢您的帮助。

【问题讨论】:

    标签: python introspection


    【解决方案1】:

    我发现IPython 对于此类任务是必不可少的。 ? (show docstring) 和 ?? (show source) 魔术命令,再加上 IPython 出色的完成系统和活动对象自省,对我来说真的很重要。

    一个示例会话:

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

    【讨论】:

      【解决方案2】:

      我想用http://pycallgraph.slowchop.com/ 或 doxygen 构建调用图。

      事实上,AST 模块和其他一些模块允许相对轻松的静态分析。我更想以某种方式进行动态分析(因为所谓的“func1”的值可能会改变,调用可能会变得完全不同)。

      【讨论】:

      • @ Bob -- +1,没听说过,听起来很有趣。谢谢。
      • @root:问题是,静态调用图对于像 python 这样的动态语言可能是不够的 :(
      猜你喜欢
      • 2018-10-09
      • 2016-08-18
      • 1970-01-01
      • 2016-01-21
      • 1970-01-01
      • 2017-08-22
      • 1970-01-01
      • 1970-01-01
      • 2011-08-03
      相关资源
      最近更新 更多