在哪里可以找到 numpy.where() 源代码? [复制]

2024-01-01

我已经找到了源码numpy.ma.where() https://docs.scipy.org/doc/numpy-1.15.0/reference/generated/numpy.ma.where.html函数,但它似乎正在调用numpy.where() https://docs.scipy.org/doc/numpy-1.15.0/reference/generated/numpy.where.html#numpy.where函数并为了更好地理解它,如果可能的话我想看一下。


大多数 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.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在哪里可以找到 numpy.where() 源代码? [复制] 的相关文章

随机推荐