如何在IPython笔记本中显示包函数的源代码 [英] How to show source code of a package function in IPython notebook

查看:402
本文介绍了如何在IPython笔记本中显示包函数的源代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

出于教学目的,我想要一个IPython笔记本显示(作为单元格的输出)功能源代码,但我希望能够在多个笔记本中引用它。因此,我希望以类似于使用%psource 魔术的方式显示功能代码,但是适当的语法突出显示。

For teaching purposes I want an IPython notebook that displays (as output from a cell) the function source code, but I want to be able to reference this in multiple notebooks. Hence I would like to display the function code, in a similar way to using the %psource magic, but appropriately syntax highlighted.

这是一个类似的问题这个问题,但我希望能够将它应用于文件中的单个函数,而不是一次性应用于完整文件。

This is a similar question to this question, but I want to be able to apply it to a single function within a file, rather than to the complete file at once.

使用上一个问题的建议我破解了一个简单的短代码:

Using the suggestion from the previous question I hacked a short code that works in simple cases:

def print_source(module, function):
    """For use inside an IPython notebook: given a module and a function, print the source code."""
    from inspect import getmembers, isfunction, getsource
    from pygments import highlight
    from pygments.lexers import PythonLexer
    from pygments.formatters import HtmlFormatter
    from IPython.core.display import HTML

    internal_module = __import__(module)

    internal_functions = dict(getmembers(internal_module, isfunction))

    return HTML(highlight(getsource(internal_functions[function]), PythonLexer(), HtmlFormatter(full=True)))

两个问题:


  1. 这个要点表明展示整个功能离子可以通过定义适当的细胞魔法来完成。是否有可能定义一个合适的单元魔术来显示单个函数,如上所述?

  2. 有没有一种方法可以在不导入整个模块的情况下执行此操作,或者更强大的方法这个?

  1. This gist suggests that showing the whole function could be done by defining appropriate cell magic. Is it possible to define an appropriate cell magic to just show a single function, as above?
  2. Is there a way of doing this without importing the entire module, or a more robust way of doing this?


推荐答案

1)魔法只是简单的功能,不难定义,你可以看看此处 自定义IPython - Config.ipynb 如果我没记错的话。我仍然不确定在你的情况下确定一个魔法是值得的。

1) Magics are just simple function not difficult to define, you could have a look here Customizing IPython - Config.ipynb if I remember correctly. still I'm not sure it is worth definig a magic in your case.

2)大部分时间,没有。您必须导入模块,因为我们需要实时代码才能知道它的定义位置。

2) Most of the time, no. You have to import the module as we need live code to know where it is defined.

一般来说,找到函数的代码并不总是非常简单。在python 3上,你总是可以访问代码对象,但大多数时候,只要你有装饰函数或动态生成函数之类的东西,它就变得很难。我想你也可以从 psource / pinfo2 激励他们让他们返回信息而不是分页。

In general, finding the code of a function is not always super easy. On python 3 you can always access the code object, but most of the time, as soon as you have things like decorated function, or dynamically generated function, it becomes difficult. I suppose you could also inspire from psource/pinfo2 and have them return info instead of paging it.

这篇关于如何在IPython笔记本中显示包函数的源代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆