如何为`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
相关产品推荐
相关产品推荐

