首页 > 解决方案 > 我在哪里可以找到 numpy.where() 源代码?

问题描述

我已经找到了numpy.ma.where()函数的来源,但它似乎正在调用numpy.where()函数,为了更好地理解它,如果可能的话,我想看看。

标签: pythonnumpy

解决方案


大多数 Python 函数是用 Python 语言编写的,但有些函数是用更原生的东西(通常是 C 语言)编写的。

常规 Python 函数(“纯 Python”)

您可以使用一些技术来询问 Python 本身函数的定义位置。可能是最便携的使用inspect模块:

>>> 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

在那个文件中,我找到了一个定义列表 ( PyMethodDef),包括:

    {"where",
        (PyCFunction)array_where,
        METH_VARARGS, NULL},

这表明 C 函数array_where是 Python 视为"where".

array_where函数在同一个文件中定义,它主要委托给该PyArray_Where函数。

简而言之

NumPy 的np.where函数是用 C 编写的,而不是 Python。PyArray_Where是一个值得一看的好地方。


推荐阅读