“可熔性”(fused types 或 type fusion)
                           
天天向上
发布: 2025-05-30 00:06:48

原创
915 人浏览过

在 Python 的标准语义中,“可熔性”(fused types 或 type fusion) 并不是一个内建的数据类型或官方术语。但这个概念常出现在如下两个语境中:


一、在 Cython 中的“可熔类型(Fused Types)”

可熔类型(Fused Types) 是 Cython 中的一个高级特性,允许你为多个 C 数据类型编写泛型代码,达到类似于 C++ 模板或 Python 泛型的效果。

示例:Cython 中定义可熔类型

from cython cimport floating

cdef fused numeric:
    int
    float
    double

cdef numeric add(numeric a, numeric b):
    return a + b

在这个例子中,numeric 就是一个 可熔类型,这个函数 add 会在编译时为每种类型(int、float、double)分别生成一个函数版本。

📘 官方文档参考:
🔗 https://cython.readthedocs.io/en/latest/src/userguide/fusedtypes.html


二、在 NumPy 中“类型融合(dtype coercion)”

NumPy 中没有“fused types”的术语,但它确实会在 多种数据类型混合时自动进行类型提升(type promotion)或合并(coercion),这有时也被误称为“可熔性”。

示例:

import numpy as np

a = np.array([1, 2, 3], dtype=np.int32)
b = np.array([1.0, 2.0, 3.0], dtype=np.float64)

c = a + b
print(c.dtype)  # float64,发生了类型提升

这不是“可熔性”的正式概念,但体现了一种数据类型“融合行为”。


三、Python 本身的泛型支持(非“可熔性”)

在 Python 3.5+ 中你可以使用 typing.Uniontyping.TypeVar 表示多个类型:

from typing import Union

def square(x: Union[int, float]) -> float:
    return x * x

这在静态类型检查中相当于支持“类型熔合”概念,但只是类型注解。


四、总结

术语所属环境含义
Fused TypesCython一种编译时泛型机制,允许函数或类支持多种 C 类型
Type PromotionNumPy多种 dtype 操作时,自动提升到兼容的类型
Union 类型注解Python typing静态类型提示中支持“多个候选类型”的形式

推荐阅读链接

  1. 📘 Cython 官方文档 Fused Types
    🔗 https://cython.readthedocs.io/en/latest/src/userguide/fusedtypes.html
  2. 📘 Python typing 文档
    🔗 https://docs.python.org/3/library/typing.html
  3. 📘 NumPy 类型系统(type coercion)说明
    🔗 https://numpy.org/doc/stable/user/basics.types.html

更多详细内容请关注其他相关文章!

发表回复 0

Your email address will not be published. Required fields are marked *