大多数 Python 函数都是用 Python 语言编写的,但有些函数是用更原生的语言(通常是 C 语言)编写的。
常规 Python 函数(“纯 Python”)
您可以使用一些技术来询问 Python 本身函数的定义位置。可能是最便携的用途inspect
module:
>>> import numpy
>>> import inspect
>>> inspect.isbuiltin(numpy.ma.where)
False
>>> inspect.getsourcefile(numpy.ma.where)
'.../numpy/core/multiarray.py'
但这不适用于本机(“内置”)函数:
>>> import numpy
>>> import inspect
>>> inspect.isbuiltin(numpy.where)
True
>>> inspect.getsourcefile(numpy.where)
TypeError: <built-in function where> is not a module, class, method, function, traceback, frame, or code object
本机(“内置”)函数
不幸的是,Python 不提供内置函数的源文件记录。您可以找出哪个模块提供了该功能:
>>> import numpy as np
>>> np.where
<built-in function where>
>>> np.where.__module__
'numpy.core.multiarray'
Python 不会帮助您找到该模块的本机 (C) 源代码,但在这种情况下,在 numpy 项目中查找具有相似名称的 C 源代码是合理的。我找到了以下文件:
numpy/core/src/multiarray/multiarraymodule.c https://github.com/numpy/numpy/blob/v1.16.1/numpy/core/src/multiarray/multiarraymodule.c#L2915
在该文件中,我找到了定义列表(PyMethodDef
) 包括:
{"where",
(PyCFunction)array_where,
METH_VARARGS, NULL},
这表明 C 函数array_where
是 Python 认为的那种"where"
.
The array_where
函数定义在同一个文件中,它主要委托给PyArray_Where
功能。
In short
NumPy's np.where
函数是用 C 编写的,而不是 Python。一个值得一看的好地方是PyArray_Where https://github.com/numpy/numpy/blob/v1.16.1/numpy/core/src/multiarray/multiarraymodule.c#L2915.