新闻详情

新闻详情

首页 / 资讯中心 / 详情

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

发布时间:2026/11/17 9:31:03来源:尧图网络
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

相关资讯

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

较早相关资讯

最新相关资讯

【外设】之大彩串口显示屏 2026/11/17 7:04:08

【外设】之大彩串口显示屏

大彩串口屏初步使用 1 .官网下载 STM32 屏幕 GUI 设计资料 http://www.gz-dc.com/category/typeid/4112 找到 STM32 Keil 工程,移植相关代码因项目而异进行移植,由于项目简单,本人只对用到的指令接口进行修改。 比如:注意事项&…

阅读更多 →
无法下载Windows系统iso文件 2026/11/17 5:42:44

无法下载Windows系统iso文件

当我遇到这个问题的时候,我打开了一个网站: 登录 然后我打算下载的时候: 突然那个官方的连接就可以下载了:

阅读更多 →
【清华代码熊】DeepSeek V4.1 Flash 后训练详解 2026/11/16 19:23:38

【清华代码熊】DeepSeek V4.1 Flash 后训练详解

📌 上期解析了 DeepSeek V4.1 Flash 模型架构改进,本期解析 DeepSeek V4.1 Flash 预训练/后训练技术: 🌟 预训练:45T 文本 多模态混合语料、直接训练 sparse attention(取消 DeepSeek V4 的 dense 冷启动&…

阅读更多 →
Shuffle-R1: Efficient RL framework for Multimodal Large Language Models via Data-centric Dynamic ... 2026/11/17 6:55:04

Shuffle-R1: Efficient RL framework for Multimodal Large Language Models via Data-centric Dynamic ...

文章主要内容和创新点 主要内容 本文聚焦于多模态大语言模型(MLLM)强化学习(RL)训练中的效率问题,提出了一个名为Shuffle-R1的框架。研究发现,当前RL训练存在两个关键缺陷: 优势值坍缩(Advantage Collapsing):批次中大多数优势值集中在零附近,导致有效梯度信号被淹…

阅读更多 →
PRvL: Quantifying the Capabilities and Risks of Large Language Models for PII Redaction 2026/11/17 5:57:47

PRvL: Quantifying the Capabilities and Risks of Large Language Models for PII Redaction

一、文章主要内容总结 本文聚焦于利用大型语言模型(LLMs)实现个人身份信息(PII)脱敏的研究,旨在解决传统脱敏方法(如基于规则的系统、领域特定命名实体识别(NER)模型)泛化能力差、跨格式/跨语境适应性弱的问题。 研究通过全面评估多种LLM架构(包括密集型LLM(D-LLM…

阅读更多 →
LLaVA-RE: Binary Image-Text Relevancy Evaluation with Multimodal Large Language Model 2026/11/16 17:28:18

LLaVA-RE: Binary Image-Text Relevancy Evaluation with Multimodal Large Language Model

文章主要内容和创新点 主要内容 本文聚焦于二进制图像-文本相关性评估任务(判断图像与文本“相关”或“不相关”),针对该任务中文本格式多样、相关性定义随场景变化等挑战,提出了基于多模态大语言模型(MLLM)的解决方案LLaVA-RE。 模型设计:LLaVA-RE基于LLaVA 1.5架构,…

阅读更多 →

今日资讯

本周资讯

本月资讯

看完文章仍有疑问?

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

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