python - 我在哪里可以找到 numpy.where() 源代码?
问题描述
我已经找到了numpy.ma.where()函数的来源,但它似乎正在调用numpy.where()函数,为了更好地理解它,如果可能的话,我想看看。
解决方案
大多数 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是一个值得一看的好地方。
推荐阅读
- javascript - 将数组中字符串的长度相加(JavaScript)
- c++ - C ++如何从子类实例化抽象父类构造函数
- java - 如果线程 ID 是 Key,那么同时更新 HashMap 是否安全?
- gradle - Gradle 会自动推断任务之间的依赖关系吗?如果有,什么时候?
- javascript - Vanilla JS:未捕获的 SyntaxError:无法在模块外使用 import 语句
- java - 如何将文件从一个 S3 客户端移动到另一个 S3 客户端
- python-3.x - 如何通过保留除一个之外的所有属性来随机改组人口?
- python - Python:将文本文件转换为二进制文件
- reactjs - 部署时反应路由器 No Match 404 不起作用?
- php - 与nodejs中的另一个程序交互