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

如何为`type`及其泛型别名覆盖类型策略?

为type及其泛型别名覆盖Hypothesis类型策略的方法

你的问题出在type[int]并非直接的type类型,而是Python里的泛型别名类型(Python 3.9+为types.GenericAlias,旧版本可能是typing._GenericAlias),所以你注册的type类型策略不会作用于它。

要解决这个问题,你需要针对泛型别名类型单独注册策略,或者同时覆盖type和泛型别名类型:

方法一:同时注册type和泛型别名类型

from hypothesis import strategies as st
import types

def type_strat(t):
    raise ValueError(t)

# 注册基础type类型的策略
st.register_type_strategy(type, type_strat)
# 注册泛型别名类型的策略
st.register_type_strategy(types.GenericAlias, type_strat)

# 现在会触发ValueError
print(st.from_type(type[int]))

方法二:针对特定泛型type别名注册

如果你只需要覆盖特定的type[int]这类类型,可以直接注册该类型:

from hypothesis import strategies as st

def type_int_strat(t):
    raise ValueError("Handling type[int]")

st.register_type_strategy(type[int], type_int_strat)

print(st.from_type(type[int]))  # 触发对应的ValueError

另外需要注意,你的代码中Rule()未定义,使用时需要确保它是已导入或自定义的对象。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 14:50:54