新闻详情

新闻详情

首页 / 资讯中心 / 详情

Hypothesis 策略的类型提示(Type Hints)完整指南:SearchStrategy、composite 与协变语义

发布时间:2026/9/25 3:31:53来源:尧图网络
Hypothesis 策略的类型提示(Type Hints)完整指南:SearchStrategy、composite 与协变语义
测试开发工具【免费下载链接】hypothesisThe property-based testing library for Python项目地址https://gitcode.com/gh_mirrors/hy/hypothesis点击查看免费下载本指南以 Hypothesis 官方文档 type-strategies.rst 为核心系统讲解如何为基于 Hypothesis 的属性测试property-based testing编写类型提示从SearchStrategy[T]泛型的基础用法、st.composite装饰器下正确标注返回值类型到SearchStrategy的协变covariance语义及其对类型检查器推断的影响。读完本文你将掌握为自定义策略函数和组合策略编写准确、可被 mypy / Pyright / Pyre 等类型检查工具验证的类型签名让策略代码享受完整的静态类型保障。所有结论均有当前仓库源码佐证。为什么策略需要类型提示Hypothesis 为所有策略以及所有返回策略的函数提供了类型提示type hints。这意味着从hypothesis.strategies常简写为st导入的每个策略构造器——如st.integers()、st.lists()——其返回值的类型都能被静态类型检查器精确识别。from hypothesis import strategies as st reveal_type(st.integers()) # SearchStrategy[int] reveal_type(st.lists(st.integers())) # SearchStrategy[list[int]]reveal_type是 mypy、Pyright、Pyre 等类型检查器提供的诊断函数它会直接在错误输出中打印表达式的推断类型。上述两行揭示出st.integers()返回SearchStrategy[int]即生成整数值的策略st.lists(st.integers())返回SearchStrategy[list[int]]即生成整数列表的策略。这些类型提示的实现位于仓库的 strategies/init.pySearchStrategy等公共符号在此重新导出源码注释明确写道“The implementation of all of these lives in_strategies.pybut we re-export them via this module to avoid exposing implementation details”真正带类型参数的定义在 strategies/_internal/strategies.py 与 strategies/_internal/core.py 中。SearchStrategy策略的类型SearchStrategy是策略的类型定义于 strategies/_internal/strategies.py#L255-L261。它是泛型generic的类型参数即为该策略所生成值的类型。该类在源码 docstring 中明确说明ASearchStrategytells Hypothesis how to generate that kind of input. This class is only part of the public API for use in type annotations, so that you can write e.g.- SearchStrategy[Foo]for your function which returnsbuilds(Foo, ...). Do not inherit from or directly instantiate this class.即SearchStrategy只用于类型标注不要继承或直接实例化它。一个典型用法是给“返回策略的函数”写返回类型注解from hypothesis import strategies as st from hypothesis.strategies import SearchStrategy # returns a strategy for normal numbers def numbers() - SearchStrategy[int | float]: return st.integers() | st.floats(allow_nanFalse, allow_infinityFalse)这里的int | float是 Python 3.10 的联合类型union type写法。st.integers() | st.floats(...)使用的是策略的|运算符等价于st.one_of(...)它把两个策略组合成一个能同时生成整数与有限浮点数的策略因此返回类型标注为SearchStrategy[int | float]完全匹配。策略strategy与返回策略的函数function的区别官方文档特意强调了一个容易混淆的点区分“策略”和“返回策略的函数”。st.integers是一个函数调用后返回一个策略因此st.integers的类型是Callable[..., SearchStrategy[int]]而s st.integers()中的s是值其类型是SearchStrategy[int]。这一区别在源码签名上体现得淋漓尽致。看 numbers.py#L123-L154 中integers的真实签名def integers( min_value: int | None None, max_value: int | None None, ) - SearchStrategy[int]:它接收可选的min_value/max_value边界参数返回SearchStrategy[int]。再看floats的签名numbers.py#L281-L291def floats( min_value: Real | None None, max_value: Real | None None, *, allow_nan: bool | None None, allow_infinity: bool | None None, allow_subnormal: bool | None None, width: Literal[16, 32, 64] 64, exclude_min: bool False, exclude_max: bool False, ) - SearchStrategy[float]:可见每个策略构造器的返回类型都被精确标注为SearchStrategy[具体值类型]这就是类型检查器能够精准推断st.integers()结果为SearchStrategy[int]的根本原因。其他常见策略的返回类型同样精确例如st.lists(element)→SearchStrategy[list[T]]见 core.py#L305st.builds(target, ...)→SearchStrategy[target类型]见 core.py#L1184st.from_type(thing)→SearchStrategy[T]其中T与传入的类型绑定见 core.py#L1273st.composite 下的类型提示写法当使用st.composite装饰器定义自定义策略时类型提示的写法有一个关键规则标注返回值的类型而不是SearchStrategy。st.composite def ordered_pairs(draw) - tuple[int, int]: n1 draw(st.integers()) n2 draw(st.integers(min_valuen1)) return (n1, n2)这里函数签名写的是- tuple[int, int]即组合策略最终产出的值的类型。st.composite装饰器会自动把它包装成一个返回SearchStrategy[tuple[int, int]]的函数——这一包装逻辑正是源码中composite的真实实现core.py#L2174-L2189if typing.TYPE_CHECKING or ParamSpec is not None: P ParamSpec(P) def composite( f: Callable[Concatenate[DrawFn, P], Ex], ) - Callable[P, SearchStrategy[Ex]]: return _composite(f)注意composite的类型签名它接收一个Callable[Concatenate[DrawFn, P], Ex]——即第一个参数是DrawFn类型draw其余参数为P返回值类型为Ex也就是你标注的返回类型——并返回Callable[P, SearchStrategy[Ex]]。所以当你在函数上写- tuple[int, int]时Ex tuple[int, int]装饰器返回的新函数类型就是SearchStrategy[tuple[int, int]]的构造器。DrawFn协议Protocol同样定义在源码中core.py#L2053-L2079其 docstring 明确写道This type only exists so that you can write type hints for functions decorated withcomposite.它的签名是def __call__(self, strategy: SearchStrategy[Ex], label: object None) - Ex:这意味着在st.composite函数内部draw(st.integers())会被推断为返回intdraw(st.text())被推断为返回str——draw的返回类型自动等于所传策略的值类型。源码 docstring 中给出了示例composite def list_and_index(draw: DrawFn) - tuple[int, str]: i draw(integers()) # type of i inferred as int s draw(text()) # type of s inferred as str return i, s底层包装CompositeStrategyst.composite的底层实现会创建一个CompositeStrategy见 core.py#L2036-L2050class CompositeStrategy(SearchStrategy): def __init__(self, definition, args, kwargs): super().__init__() self.definition definition self.args args self.kwargs kwargs def do_draw(self, data): return self.definition(data.draw, *self.args, **self.kwargs)它在执行do_draw时把 ConjectureData 的draw方法作为第一个参数传给原函数这正是你在st.composite函数中接收的draw参数的来源。这一实现印证了类型层面DrawFn协议对应运行时真正的data.draw调用接口两者一一对应。补充给 draw 参数也加上类型虽然官方示例中draw参数未加注解但为了更好的类型检查体验可以显式标注from hypothesis.strategies import DrawFn st.composite def ordered_pairs(draw: DrawFn) - tuple[int, int]: n1 draw(st.integers()) n2 draw(st.integers(min_valuen1)) return (n1, n2)DrawFn可以从hypothesis.strategies导入已在 strategies/init.py 的__all__中导出见该文件第 68 行。这样draw(...)的返回值类型就能被静态推断n1、n2都是int进而min_valuen1的传参也能通过类型检查。SearchStrategy 的协变性Covariance含义SearchStrategy是协变covariant的即如果B AB 是 A 的子类型那么SearchStrategy[B] SearchStrategy[A]SearchStrategy[B]是SearchStrategy[A]的子类型。用官方文档的例子策略st.from_type(Dog)是策略st.from_type(Animal)的子类型其中Dog继承自Animal。这符合直觉——凡是能生成Animal的地方都能接受一个只生成Dog的策略。源码证据协变语义在 strategies/_internal/strategies.py#L64-L67 中通过TypeVar的covariantTrue参数实现if TYPE_CHECKING: Ex TypeVar(Ex, covariantTrue, defaultAny) else: Ex TypeVar(Ex, covariantTrue) class SearchStrategy(Generic[Ex]): # L255Ex声明为covariantTrue的TypeVarSearchStrategy继承自Generic[Ex]。当类型检查器看到SearchStrategy[Dog]与SearchStrategy[Animal]时就能依据Dog Animal推导出前者是后者的子类型。协变在实践中的价值协变让策略可以在函数参数与返回位置灵活替换。例如下面这个接受“任意动物策略”的函数def run_experiment(animals: SearchStrategy[Animal]) - None: ... run_experiment(st.from_type(Dog)) # OK协变SearchStrategy[Dog] 可传给 SearchStrategy[Animal] run_experiment(st.from_type(Animal)) # OK如果把SearchStrategy设计成不变invariant的则run_experiment(st.from_type(Dog))会直接报类型错误即使从语义上完全合理。正是协变设计让这种直观的用法得以通过类型检查。需要说明的是SearchStrategy的协变是在类型层面由TypeVar(covariantTrue)声明的性质类型检查器mypy、Pyright、Pyre 等在静态分析时依据该声明进行子类型推断运行时并不存在子类型关系的强制检查。类型提示的验证与测试保障Hypothesis 仓库自身就用测试保障了这些类型提示的准确性。例如 tests/cover/test_annotations.py 中有如下断言第 99 行附近assert sig_comp.return_annotation st.SearchStrategy[int]它验证组合策略函数签名的返回注解确实是st.SearchStrategy[int]。此外仓库还维护了whole_repo_tests/types/目录下的类型测试套件test_mypy.py、test_pyright.py、test_hypothesis.py用真实类型检查器对整仓库代码进行验证确保策略 API 的类型提示不会退化。实践小结场景正确的类型标注说明函数返回一个策略- SearchStrategy[int]返回的是“策略”本身使用st.composite定义策略- tuple[int, int]标注值的类型装饰器会包装为SearchStrategy[tuple[int, int]]构造器st.composite函数内部draw: DrawFn或省略draw(strategy)的返回值类型自动等于策略值类型多个策略组合SearchStrategy[int \| float]用\|或st.one_of组合后类型取联合核心要点回顾SearchStrategy[T]是策略的泛型类型T是策略生成值的类型它是公共 API 中仅用于类型标注的类不要继承或实例化st.integers函数的类型是Callable[..., SearchStrategy[int]]而s st.integers()值的类型是SearchStrategy[int]两者务必区分st.composite下标注返回值的类型而不是SearchStrategy[...]装饰器负责自动包装SearchStrategy是协变的B A蕴含SearchStrategy[B] SearchStrategy[A]这让策略在参数与返回值位置可以灵活替换其语义由源码中TypeVar(Ex, covariantTrue)声明保证。按照上述规则为策略代码添加类型提示即可让 mypy、Pyright、Pyre 等工具在编写阶段发现策略类型不匹配的问题让属性测试代码同样享受现代静态类型检查带来的安全性与可维护性。赞分享测试开发工具【免费下载链接】hypothesisThe property-based testing library for Python项目地址https://gitcode.com/gh_mirrors/hy/hypothesis点击查看免费下载相关推荐如何快速捕获网页视频猫抓浏览器扩展的终极指南如何快速捕获网页视频猫抓浏览器扩展的终极指南 猫抓cat catch浏览器扩展是一款专业的网页资源嗅探工具它能自动检测并捕获网页中的视频资源从普通MP音视频Loguru API 参考指南从 logger 方法到类型提示Type Hints的完整解读Loguru API 参考指南从 logger 方法到类型提示Type Hints的完整解读 导读 本文以 loguru 官方 API 参考文档 doc开发工具Hello-Python类型提示Type Hints代码规范Hello Python类型提示Type Hints代码规范 为什么需要Type Hints类型提示 你是否曾在维护Python代码时遇到过这个变量到示例工程教程上一篇Falco社区赞助商权益套餐与激活下一篇如何使用kss-node创建自动化CSS文档5分钟快速入门教程创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考
网站建设高端定制企业官网
RELATED

相关资讯

更多精彩内容,欢迎继续阅读

较早相关资讯

最新相关资讯

CiLocks ADB连接问题排查:unauthorized、no devices等8个常见报错速查 2026/9/25 4:09:25

CiLocks ADB连接问题排查:unauthorized、no devices等8个常见报错速查

CiLocks ADB连接问题排查:unauthorized、no devices等8个常见报错速查 【免费下载链接】CiLocks Crack Interface lockscreen, Metasploit and More Android/IOS Hacking 项目地址: https://gitcode.com/GitHub_Trending/ci/CiLocks CiLocks 是一款免费的 An…

阅读更多 →
AI客服系统响应时长从50分钟到2分半:Token管理、幻觉治理与多模态处理实战 2026/9/25 4:09:19

AI客服系统响应时长从50分钟到2分半:Token管理、幻觉治理与多模态处理实战

1. 项目背景与核心目标拆解1.1 为什么响应时长是客服系统的生死线50分钟到2分半,这个数字对比放在任何一家做客服业务的公司里,都足够让技术负责人心跳加速。我所在的项目组从零搭建了一套AI客服系统,上线前三个月,平均首次响应时…

阅读更多 →
ng-zorro-antd Code Editor 组件全指南:在 Angular 中集成 monaco-editor 的加载模式、配置与实战 2026/9/25 4:09:19

ng-zorro-antd Code Editor 组件全指南:在 Angular 中集成 monaco-editor 的加载模式、配置与实战

UI组件前端 【免费下载链接】ng-zorro-antd Angular UI Component Library based on Ant Design 项目地址: https://gitcode.com/gh_mirrors/ng/ng-zorro-antd 点击查看 免费下载 导读 nz-code-editor 是 ng-zorro-antd 基于微软 monaco-editor 封装的开箱即用型 …

阅读更多 →
Hypothesis 策略适配指南:用 map、filter 与 assume 精确控制测试数据生成 2026/9/25 4:09:19

Hypothesis 策略适配指南:用 map、filter 与 assume 精确控制测试数据生成

测试开发工具 【免费下载链接】hypothesis The property-based testing library for Python 项目地址: https://gitcode.com/gh_mirrors/hy/hypothesis 点击查看 免费下载 本篇指南聚焦 Hypothesis(Python 属性基测试库)中"适配策略&qu…

阅读更多 →
金融AI审计落地:风险矩阵、证据链与FDE实操指南 2026/9/25 4:09:13

金融AI审计落地:风险矩阵、证据链与FDE实操指南

1. 金融AI落地的审计困境与破局思路金融行业对AI的态度一直很拧巴。业务部门想要更快的审批速度、更准的风险定价、更低的运营成本,技术团队手里也有大模型和机器学习工具,但每次项目推进到合规审查环节,就会被一连串问题卡住:这个…

阅读更多 →
HR效率革命:WorkBuddy加Skill实战,从简历筛选到薪酬核算全自动化 2026/9/25 4:09:13

HR效率革命:WorkBuddy加Skill实战,从简历筛选到薪酬核算全自动化

1. 从HR的日常痛点说起:为什么WorkBuddy加Skill能让人“爽爆”HR这个岗位,外行看着光鲜,内行才知道有多琐碎。招聘季一天筛几百份简历,眼睛都快看瞎;员工入职要收集身份证、学历证、银行卡、体检报告,少一样…

阅读更多 →

今日资讯

本周资讯

本月资讯

看完文章仍有疑问?

联系尧图顾问,获取一对一建站咨询

立即免费咨询 📞 400-888-8888
📞 ✉