如何检索 Python 函数的源代码

学习使用 inspect 和 dill 库来访问 Python 函数的源代码。
296 位读者喜欢这篇文章。
code.org keynote address

Opensource.com

有时我们想知道一些函数的源代码是什么样的,或者它们在哪里,或者我们需要将源代码作为字符串进行操作。在这些情况下,我们需要一种方便的方法来检索我们的 Python 函数的源代码。

有两个 Python 库可能会有所帮助

  • inspect 是一个内置的标准库
  • dill 是一个第三方库

inspect

inspect 是一个内置库。在您的计算机上安装 Python 后,它就已经存在了。inspect 模块提供了几个有用的函数,以帮助您获取有关 活动对象 的信息,例如模块、类、方法、函数、回溯、帧对象和代码对象。在其众多功能中,检索函数源代码的能力尤为突出。

在 [1] 中
import pandas
import inspect
在 [3] 中
source_DF = inspect.getsource(pandas.DataFrame)
print(type(source_DF))

<<class 'str'>>

在 [4] 中
print(len(source_DF))

218432

在 [5] 中
print(source_DF[:200])

class DataFrame(NDFrame):

   
""" 二维大小可变,可能异构的表格数据

    结构,带有标记轴(行和列)。算术运算

    在行 a 上对齐

在 [6] 中
source_file_DF = inspect.getsourcefile(pandas.DataFrame)
print(source_file_DF)

D:\Users\dengdong\AppData\Local\Continuum\anaconda3\lib\site-packages\pandas\core\frame.py

在 [7] 中
sourcelines_DF = inspect.getsourcelines(pandas.DataFrame)
print(type(sourcelines_DF))
print(len(sourcelines_DF))
print(type(sourcelines_DF[0]))

<class 'tuple'>

2

<class 'list'>

IPythonJupyter 中,我们也可以使用此方法来检索我们在控制台中定义的函数的源代码。

在 [9] 中
def test(x):

   return x*2

print(inspect.getsource(test))

def test(x): return x*2

在 [10] 中
print(inspect.getsourcefile(test))

<ipython-input-9-70ac3e17460c>

在 [11] 中
print(inspect.getsourcelines(test))

(['def test(x):\n', ' return x*2\n'], 1)

请注意,检索自定义函数的源代码仅在 IPython 或 Jupyter 中有效。如果我们使用纯 Python 并以交互方式定义函数,我们将遇到错误 IOError: could not get source code 并且将无法检索源代码。这是因为它的设置仅支持从 文件加载 的对象,而不支持交互式会话。

dill

dill 扩展了 Python 的 pickle 模块,用于将 Python 对象序列化和反序列化为大多数内置 Python 类型。同时,它还可以检索您的 Python 对象的源代码。请注意,dill 不是标准库,因此您必须单独安装它。

它的 API 与 inspect 的非常相似。

在 [6] 中
import dill

source_DF = dill.source.getsource(pandas.DataFrame)
print(type(source_DF))
print(len(source_DF))
print(source_DF[:200])

source_file_DF = dill.source.getsourcefile(pandas.DataFrame)
print(source_file_DF)

sourcelines_DF = dill.source.getsourcelines(pandas.DataFrame)
print(type(sourcelines_DF))
print(len(sourcelines_DF))
print(type(sourcelines_DF[0]))

<type 'str'>
195262
class DataFrame(NDFrame):
    """ Two-dimensional size-mutable, potentially heterogeneous tabular data
    structure with labeled axes (rows and columns). Arithmetic operations
    align on both row a
/Users/XD/anaconda/lib/python2.7/site-packages/pandas/core/frame.py
<type 'tuple'>
2
<type 'list'>

 

然而,dillinspect 之间的一个很大区别是,dill 的检索功能支持纯 Python 控制台中的自定义对象。

标签
User profile image.
来自中国,现在居住在新加坡。我在本科和硕士期间都主修数学。但后来我发现处理编码更有趣。从工程角度思考真的对我帮助很大。有关更多信息,请访问我的网站 XD-DENG.com。

评论已关闭。

Creative Commons License本作品根据 Creative Commons Attribution-Share Alike 4.0 International License 许可。
© . All rights reserved.