This module provides the array_namespace_info class implementing the Array API inspection namespace for NumPy, enabling users to query library capabilities, default devices, default data types, supported data types by kind, and available devices following the array API standard.
graph TD
A[User calls np.__array_namespace_info__()] --> B[Create __array_namespace_info__ instance]
B --> C{User calls method}
C --> D[capabilities()]
C --> E[default_device()]
C --> F[default_dtypes(device)]
C --> G[dtypes(device, kind)]
C --> H[devices()]
D --> I[Return dict with boolean indexing, data-dependent shapes, max dimensions]
E --> J[Return 'cpu' string]
F --> K{Validate device parameter}
K -- Valid --> L[Return default dtypes dict]
K -- Invalid --> M[Raise ValueError]
G --> N{Validate device parameter}
N -- Valid --> O{Validate kind parameter}
O -- None --> P[Return all API dtypes]
O -- 'bool' --> Q[Return bool dtype]
O -- 'signed integer' --> R[Return signed int dtypes]
O -- 'unsigned integer' --> S[Return unsigned int dtypes]
O -- 'integral' --> T[Return all integer dtypes]
O -- 'real floating' --> U[Return float dtypes]
O -- 'complex floating' --> V[Return complex dtypes]
O -- 'numeric' --> W[Return all numeric dtypes]
O -- Tuple --> X[Recursively merge dtypes]
O -- Invalid --> Y[Raise ValueError]
N -- Invalid --> Z[Raise ValueError]
H --> AA[Return ['cpu'] list]
Global Scope
├── Imports (from numpy._core)
│ ├── bool, dtype
│ ├── int8, int16, int32, int64, intp
│ ├── uint8, uint16, uint32, uint64
│ ├── float32, float64
│ └── complex64, complex128
├── @set_module decorator function
└── __array_namespace_info__ class
├── capabilities() method
├── default_device() method
├── default_dtypes(device) method
├── dtypes(device, kind) method
└── devices() methodNumPy boolean data type
类型:numpy.dtype
NumPy 64-bit complex number data type (two 32-bit floats)
类型:numpy.dtype
NumPy 128-bit complex number data type (two 64-bit floats)
类型:numpy.dtype
NumPy data type object/class for creating data type instances
类型:type
NumPy 32-bit floating point data type
类型:numpy.dtype
NumPy 64-bit floating point data type (double precision)
类型:numpy.dtype
NumPy 8-bit signed integer data type
类型:numpy.dtype
NumPy 16-bit signed integer data type
类型:numpy.dtype
NumPy 32-bit signed integer data type
类型:numpy.dtype
NumPy 64-bit signed integer data type
类型:numpy.dtype
NumPy platform-dependent integer type for indexing (signed)
类型:numpy.dtype
NumPy 8-bit unsigned integer data type
类型:numpy.dtype
NumPy 16-bit unsigned integer data type
类型:numpy.dtype
NumPy 32-bit unsigned integer data type
类型:numpy.dtype
NumPy 64-bit unsigned integer data type
类型:numpy.dtype
set_module 是一个装饰器工厂函数,用于将函数或类的 __module__ 属性设置为指定的值,从而使其在文档中显示为属于特定模块。
参数:
module:str,要设置的模块名称(如'numpy')
返回值:Callable,装饰器函数,用于将目标对象的 __module__ 属性设置为指定的模块名
flowchart TD
A[接收 module 参数] --> B{验证 module 是否为字符串}
B -->|是| C[返回装饰器函数]
B -->|否| D[抛出 TypeError]
C --> E{被装饰对象是类还是函数}
E -->|类| F[设置类的 __module__ 属性]
E -->|函数| G[设置函数的 __module__ 属性]
F --> H[返回修改后的类]
G --> I[返回修改后的函数]
def set_module(module):
"""
设置函数或类的模块属性。
Parameters
----------
module : str
要设置的模块名称。
Returns
-------
callable
一个装饰器函数,用于将目标对象的 __module__ 属性设置为指定的模块名。
Examples
--------
>>> @set_module('numpy')
... class MyClass:
... pass
>>> MyClass.__module__
'numpy'
"""
def decorator(obj):
"""
实际的装饰器函数,用于设置对象的 __module__ 属性。
Parameters
----------
obj : object
要装饰的类或函数对象。
Returns
-------
object
设置了 __module__ 属性的对象。
"""
obj.__module__ = module
return obj
return decorator在代码中的实际使用方式:
from numpy._utils import set_module
@set_module('numpy') # 装饰器将 __array_namespace_info__ 类的 __module__ 属性设置为 'numpy'
class __array_namespace_info__:
# 类定义...
pass这样当访问 __array_namespace_info__.__module__ 时,会返回 'numpy' 而不是默认的模块名。
该方法返回NumPy数组API库的能力信息字典,包含布尔索引支持、依赖数据的形状支持以及最大维度数。
参数:
self:__array_namespace_info__类实例,隐式参数,无需显式传入
返回值:dict,返回包含NumPy数组API库能力的字典,具有以下键值对:
"boolean indexing":bool,表示是否支持布尔索引,NumPy始终为True"data-dependent shapes":bool,表示是否支持数据依赖的输出形状,NumPy始终为True"max dimensions":int,表示支持的最大维度数,值为64
flowchart TD
A[开始] --> B[创建能力字典]
B --> C{返回字典}
C --> D[结束]
B -->|"boolean indexing": True| C
B -->|"data-dependent shapes": True| C
B -->|"max dimensions": 64| C
def capabilities(self):
"""
Return a dictionary of array API library capabilities.
The resulting dictionary has the following keys:
- **"boolean indexing"**: boolean indicating whether an array library
supports boolean indexing. Always ``True`` for NumPy.
- **"data-dependent shapes"**: boolean indicating whether an array
library supports data-dependent output shapes. Always ``True`` for
NumPy.
See
https://data-apis.org/array-api/latest/API_specification/generated/array_api.info.capabilities.html
for more details.
See Also
--------
__array_namespace_info__.default_device,
__array_namespace_info__.default_dtypes,
__array_namespace_info__.dtypes,
__array_namespace_info__.devices
Returns
-------
capabilities : dict
A dictionary of array API library capabilities.
Examples
--------
>>> info = np.__array_namespace_info__()
>>> info.capabilities()
{'boolean indexing': True,
'data-dependent shapes': True,
'max dimensions': 64}
"""
# 返回包含NumPy数组API能力信息的字典
# 1. boolean indexing: NumPy支持布尔索引,始终返回True
# 2. data-dependent shapes: NumPy支持数据依赖的输出形状,始终返回True
# 3. max dimensions: NumPy支持的最大维度数为64
return {
"boolean indexing": True,
"data-dependent shapes": True,
"max dimensions": 64,
}返回 NumPy 数组的默认设备。对于 NumPy,此方法始终返回 'cpu',因为 NumPy 主要在 CPU 上运行。
参数:
- 该方法无参数(除隐式
self参数)
返回值:str,返回默认设备字符串 'cpu'。
flowchart TD
A[开始 default_device 方法] --> B{直接返回}
B -->|是| C[返回字符串 'cpu']
C --> D[结束方法]
def default_device(self):
"""
The default device used for new NumPy arrays.
For NumPy, this always returns ``'cpu'``.
See Also
--------
__array_namespace_info__.capabilities,
__array_namespace_info__.default_dtypes,
__array_namespace_info__.dtypes,
__array_namespace_info__.devices
Returns
-------
device : str
The default device used for new NumPy arrays.
Examples
--------
>>> info = np.__array_namespace_info__()
>>> info.default_device()
'cpu'
"""
# NumPy 作为 CPU 密集型库,默认设备始终为 'cpu'
# 这是因为 NumPy 的核心计算在 CPU 上执行
return "cpu"该方法返回 NumPy 数组的默认数据类型信息。对于 NumPy,始终返回一个包含四个键的字典,分别对应实数浮点数、复数浮点数、整数和索引类型的默认数据类型。
参数:
device:str,可选参数,用于指定获取默认数据类型的设备。对于 NumPy,仅支持'cpu'。如果传入其他值,将抛出ValueError异常。
返回值:dict,一个描述新 NumPy 数组所用默认数据类型的字典,包含以下键值对:
"real floating":对应numpy.float64"complex floating":对应numpy.complex128"integral":对应numpy.intp"indexing":对应numpy.intp
flowchart TD
A[开始 default_dtypes] --> B{device 是否有效}
B -->|否| C[抛出 ValueError: 设备不支持,仅支持 cpu]
B -->|是| D[返回默认数据类型字典]
D --> E["real floating": dtype(float64)]
D --> F["complex floating": dtype(complex128)]
D --> G["integral": dtype(intp)]
D --> H["indexing": dtype(intp)]
def default_dtypes(self, *, device=None):
"""
The default data types used for new NumPy arrays.
For NumPy, this always returns the following dictionary:
- **"real floating"**: ``numpy.float64``
- **"complex floating"**: ``numpy.complex128``
- **"integral"**: ``numpy.intp``
- **"indexing"**: ``numpy.intp``
Parameters
----------
device : str, optional
The device to get the default data types for. For NumPy, only
``'cpu'`` is allowed.
Returns
-------
dtypes : dict
A dictionary describing the default data types used for new NumPy
arrays.
See Also
--------
__array_namespace_info__.capabilities,
__array_namespace_info__.default_device,
__array_namespace_info__.dtypes,
__array_namespace_info__.devices
Examples
--------
>>> info = np.__array_namespace_info__()
>>> info.default_dtypes()
{'real floating': numpy.float64,
'complex floating': numpy.complex128,
'integral': numpy.int64,
'indexing': numpy.int64}
"""
# 验证设备参数是否合法,NumPy 仅支持 'cpu' 设备
if device not in ["cpu", None]:
raise ValueError(
'Device not understood. Only "cpu" is allowed, but received:'
f' {device}'
)
# 返回包含默认数据类型的字典
return {
"real floating": dtype(float64), # 实数浮点数默认类型
"complex floating": dtype(complex128), # 复数浮点数默认类型
"integral": dtype(intp), # 整数默认类型
"indexing": dtype(intp), # 索引默认类型
}返回 NumPy 支持的数组 API 数据类型,根据设备和孩子过滤。
参数:
device:str | None,可选,设备类型。对于 NumPy,仅支持'cpu'。kind:str | tuple[str] | None,可选,要返回的数据类型种类。如果为None,返回所有数据类型。
返回值:dict,将数据类型名称映射到对应的 NumPy 数据类型。
flowchart TD
A[开始 dtypes] --> B{device 有效?}
B -->|否| C[抛出 ValueError]
B -->|是| D{kind is None?}
D -->|是| E[返回所有数据类型字典]
D -->|否| F{kind == 'bool'?}
F -->|是| G[返回布尔类型]
F -->|否| H{kind == 'signed integer'?}
H -->|是| I[返回有符号整数类型]
H -->|否| J{kind == 'unsigned integer'?}
J -->|是| K[返回无符号整数类型]
J -->|否| L{kind == 'integral'?}
L -->|是| M[返回所有整数类型]
L -->|否| N{kind == 'real floating'?}
N -->|是| O[返回实数浮点类型]
N -->|否| P{kind == 'complex floating'?}
P -->|是| Q[返回复数浮点类型]
P -->|否| R{kind == 'numeric'?}
R -->|是| S[返回所有数值类型]
R -->|否| T{kind 是元组?}
T -->|是| U[递归合并各类型结果]
T -->|否| V[抛出 ValueError 不支持的种类]
def dtypes(self, *, device=None, kind=None):
"""
The array API data types supported by NumPy.
Note that this function only returns data types that are defined by
the array API.
Parameters
----------
device : str, optional
The device to get the data types for. For NumPy, only ``'cpu'`` is
allowed.
kind : str or tuple of str, optional
The kind of data types to return. If ``None``, all data types are
returned. If a string, only data types of that kind are returned.
If a tuple, a dictionary containing the union of the given kinds
is returned. The following kinds are supported:
- ``'bool'``: boolean data types (i.e., ``bool``).
- ``'signed integer'``: signed integer data types (i.e., ``int8``,
``int16``, ``int32``, ``int64``).
- ``'unsigned integer'``: unsigned integer data types (i.e.,
``uint8``, ``uint16``, ``uint32``, ``uint64``).
- ``'integral'``: integer data types. Shorthand for ``('signed
integer', 'unsigned integer')``.
- ``'real floating'``: real-valued floating-point data types
(i.e., ``float32``, ``float64``).
- ``'complex floating'``: complex floating-point data types (i.e.,
``complex64``, ``complex128``).
- ``'numeric'``: numeric data types. Shorthand for ``('integral',
'real floating', 'complex floating')``.
Returns
-------
dtypes : dict
A dictionary mapping the names of data types to the corresponding
NumPy data types.
See Also
--------
__array_namespace_info__.capabilities,
__array_namespace_info__.default_device,
__array_namespace_info__.default_dtypes,
__array_namespace_info__.devices
Examples
--------
>>> info = np.__array_namespace_info__()
>>> info.dtypes(kind='signed integer')
{'int8': numpy.int8,
'int16': numpy.int16,
'int32': numpy.int32,
'int64': numpy.int64}
"""
# 验证设备参数,只能是 'cpu' 或 None
if device not in ["cpu", None]:
raise ValueError(
'Device not understood. Only "cpu" is allowed, but received:'
f' {device}'
)
# 如果没有指定 kind,返回所有数组 API 支持的数据类型
if kind is None:
return {
"bool": dtype(bool),
"int8": dtype(int8),
"int16": dtype(int16),
"int32": dtype(int32),
"int64": dtype(int64),
"uint8": dtype(uint8),
"uint16": dtype(uint16),
"uint32": dtype(uint32),
"uint64": dtype(uint64),
"float32": dtype(float32),
"float64": dtype(float64),
"complex64": dtype(complex64),
"complex128": dtype(complex128),
}
# 根据 kind 参数返回对应的数据类型子集
if kind == "bool":
return {"bool": bool}
if kind == "signed integer":
return {
"int8": dtype(int8),
"int16": dtype(int16),
"int32": dtype(int32),
"int64": dtype(int64),
}
if kind == "unsigned integer":
return {
"uint8": dtype(uint8),
"uint16": dtype(uint16),
"uint32": dtype(uint32),
"uint64": dtype(uint64),
}
if kind == "integral":
return {
"int8": dtype(int8),
"int16": dtype(int16),
"int32": dtype(int32),
"int64": dtype(int64),
"uint8": dtype(uint8),
"uint16": dtype(uint16),
"uint32": dtype(uint32),
"uint64": dtype(uint64),
}
if kind == "real floating":
return {
"float32": dtype(float32),
"float64": dtype(float64),
}
if kind == "complex floating":
return {
"complex64": dtype(complex64),
"complex128": dtype(complex128),
}
if kind == "numeric":
return {
"int8": dtype(int8),
"int16": dtype(int16),
"int32": dtype(int32),
"int64": dtype(int64),
"uint8": dtype(uint8),
"uint16": dtype(uint16),
"uint32": dtype(uint32),
"uint64": dtype(uint64),
"float32": dtype(float32),
"float64": dtype(float64),
"complex64": dtype(complex64),
"complex128": dtype(complex128),
}
# 如果 kind 是元组,递归合并多个种类的结果
if isinstance(kind, tuple):
res = {}
for k in kind:
res.update(self.dtypes(kind=k))
return res
# 如果 kind 不匹配任何支持的种类,抛出错误
raise ValueError(f"unsupported kind: {kind!r}")该方法返回 NumPy 支持的设备列表。由于 NumPy 是 CPU-only 的库,该方法始终返回包含字符串 'cpu' 的列表,用于表示默认的计算设备。
参数: 无(仅包含隐式参数 self)
返回值:list of str,返回 NumPy 支持的设备列表,对于 NumPy 始终返回 ['cpu']。
flowchart TD
A[开始 devices 方法] --> B{方法调用}
B --> C[返回列表 ['cpu']]
C --> D[结束方法]
style A fill:#f9f,stroke:#333
style C fill:#9f9,stroke:#333
style D fill:#f9f,stroke:#333
def devices(self):
"""
The devices supported by NumPy.
For NumPy, this always returns ``['cpu']``.
Returns
-------
devices : list of str
The devices supported by NumPy.
See Also
--------
__array_namespace_info__.capabilities,
__array_namespace_info__.default_device,
__array_namespace_info__.default_dtypes,
__array_namespace_info__.dtypes
Examples
--------
>>> info = np.__array_namespace_info__()
>>> info.devices()
['cpu']
"""
# NumPy 仅支持 CPU 设备,返回包含 'cpu' 的列表
# 这是因为 NumPy 是 CPU-only 的数值计算库
return ["cpu"]提供Array API标准定义的检查函数,用于查询NumPy的库能力、默认设备、数据类型和设备支持等信息。
返回NumPy的Array API库能力字典,包含布尔索引支持、数据依赖形状和最大维度数。
返回NumPy的默认设备,由于NumPy仅支持CPU计算,因此始终返回'cpu'。
返回NumPy新建数组时使用的默认数据类型字典,包括实数浮点型、复数浮点型、整型和索引类型。
根据设备和数据类型种类查询NumPy支持的Array API数据类型,可按种类过滤返回布尔、整型、浮点型、复数型等数据类型。
返回NumPy支持的设备列表,由于NumPy仅支持CPU计算,因此始终返回['cpu']。
对不支持的device参数抛出ValueError,对不支持的kind参数抛出ValueError,确保只有符合Array API规范的值才能被接受。
通过dtype()函数将NumPy内部类型转换为Array API标准类型,实现两种体系之间的数据类型映射和转换。
- default_dtypes 返回值与文档不一致:方法中返回
dtype(intp),但文档示例显示numpy.int64。由于intp是平台相关的(32位系统上可能是 int32),这会导致文档与实际行为不一致。 - dtypes 方法递归调用丢失 device 参数:当
kind为 tuple 时,递归调用self.dtypes(kind=k)没有传递device参数。虽然当前不影响 CPU,但违反了 DRY 原则且未来可能引发问题。 - dtypes 方法存在大量重复代码:不同 kind 的返回值字典有大量重复定义(如 "integral" 包含 "signed integer" 和 "unsigned integer" 的全部内容),维护性差。
- 类设计不必要:该类没有任何实例变量或状态,所有方法都是静态的(不依赖 self),更适合作为模块级函数或使用 @staticmethod。
- 硬编码值缺乏灵活性:
capabilities()中的 "max dimensions": 64 和devices()返回的 ["cpu"] 都是硬编码的,与 Array API 标准耦合过紧。 - 类型注解缺失:作为公共 API 缺少类型提示(type hints),降低了对 IDE 和静态分析工具的支持。
- 错误消息格式不统一:default_dtypes 和 dtypes 方法的 ValueError 消息格式略有差异。
- 统一 default_dtypes 返回类型:考虑在文档中说明 intp 的平台依赖性,或统一返回 int64 以保持一致性。
- 重构 dtypes 方法:使用字典映射或数据驱动的方式定义 kind 与返回值的对应关系,消除重复代码,并在递归调用时传递 device 参数。
- 改为模块函数或添加实例状态:如果不需要保持与旧代码的兼容性,可将类改为模块级函数集合;若需保留类结构,可考虑添加实例变量(如配置的设备)以体现类的必要性。
- 提取常量:将硬编码的值(如 64、"cpu")提取为模块级常量或从配置读取。
- 添加类型注解:为所有方法添加参数和返回值的类型注解,提升 API 可用性。
- 统一错误处理:标准化错误消息格式,便于调用者统一处理。
本模块旨在实现 Array API 标准中定义的检查函数(inspection functions),为 NumPy 提供符合 Array API 规范的元信息查询能力。设计约束包括:仅支持 CPU 设备、严格遵循 Array API 规范的数据类型名称和返回值格式、保持与 NumPy 现有 API 风格一致。
代码中的错误处理主要体现在参数验证上:default_dtypes() 和 dtypes() 方法均对 device 参数进行校验,当传入非 None 或 "cpu" 的值时抛出 ValueError 并附带详细的错误信息。dtypes() 方法还验证 kind 参数,支持字符串或字符串元组,不支持的 kind 会抛出 ValueError。异常设计遵循 NumPy 惯例,使用具体异常类型(ValueError)并提供清晰的错误描述。
本模块依赖 numpy._core 中的数据类型常量(bool、complex64、complex128、dtype、float32、float64、int8、int16、int32、int64、intp、uint8、uint16、uint32、uint64)以及 numpy._utils 中的 set_module 装饰器。接口契约遵循 Array API 规范:所有方法返回固定结构的数据(字典或列表),数据类型返回值使用 numpy.dtype 对象。
由于本模块仅返回预定义的静态信息(无任何计算逻辑),性能开销极低。方法调用时间复杂度为 O(1),无内存分配或计算密集型操作。设计上通过直接返回字典字面量避免运行时开销。
应包含单元测试验证:各方法返回值的正确性(键名、值类型、值内容);参数验证测试(device 参数非法值、kind 参数非法值);边界情况测试(kind 为空元组、kind 包含重复值);与 Array API 规范的一致性测试。
本模块与 NumPy 版本紧密绑定,依赖于 numpy._core 和 numpy._utils 的内部实现。Array API 标准版本为 Latest(data-apis.org/array-api),未来标准变更可能需要调整返回值结构。set_module 装饰器确保模块归属为 numpy 命名空间。
遵循 NumPy 内部命名约定:类名使用双下划线前缀后缀(__array_namespace_info__)表示这是模块级特殊对象;方法名使用 snake_case;字典键使用空格分隔的字符串(如 "boolean indexing"),符合 Array API 规范要求。
文档中已包含各方法的完整示例,涵盖:获取 capabilities 并验证键值;获取 default_device 验证返回 "cpu";获取 default_dtypes 验证四种默认类型;通过不同 kind 参数获取 dtypes;获取 devices 验证返回列表。