gpt4 book ai didi

python - 如何在 IPython notebook 中显示包函数的源代码

转载 作者:太空狗 更新时间:2023-10-29 18:08:17 25 4
gpt4 key购买 nike

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

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

根据上一个问题的建议,我破解了一段适用于简单情况的短代码:

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. This gist建议可以通过定义适当的单元魔术来显示整个功能。是否可以定义一个适当的单元魔术来仅显示一个函数,如上所述?
  2. 有没有一种方法可以在不导入整个模块的情况下执行此操作,或者有更可靠的方法来执行此操作?

最佳答案

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

2) 大多数时候,不会。您必须导入模块,因为我们需要实时代码才能知道它的定义位置。

一般来说,找到一个函数的代码并不总是那么容易。在 python 3 上,您始终可以访问代码对象,但大多数时候,一旦您拥有装饰函数或动态生成的函数之类的东西,它就会变得困难。我想您也可以从 psource/pinfo2 获得启发,让它们返回信息而不是分页。

关于python - 如何在 IPython notebook 中显示包函数的源代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20665118/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com