You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为Cython的fused_type参数设置默认值?类型错误求助

解决Cython fused类型参数默认值报错问题

问题原因

你给fused类型参数设了默认值0,但因为test_type包含str分支,Cython生成str版本的函数时,会要求默认值是unicode类型(即str),但你传的0是int,类型不匹配,所以抛出TypeError: Expected unicode, got int。

解决方案

不能给包含多类型的fused参数直接设单一默认值,得针对每个类型分支单独处理,推荐用None作为统一默认值,在函数内部根据当前分支类型赋值:

ctypedef fused test_type:
    double
    int
    str
    MyObject

def test_point(self, a : test_type = None):
    if a is None:
        if test_type is int:
            a = 0
        elif test_type is double:
            a = 0.0
        elif test_type is str:
            a = ""
        elif test_type is MyObject:
            a = MyObject()  # 假设MyObject有默认构造方法
    print("hahah")

补充思路

如果不需要str分支支持默认值调用,或者可以接受强制指定类型调用,也可以在调用时显式指定类型,但这种方式灵活性差,不如上面的方法通用。

内容的提问来源于stack exchange,提问作者Punreach Rany

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.19 14:05:58