如何为sorted(set(lst))中的T添加类型提示以通过类型检查?
解决类型变量T的复合约束问题
你的代码报错是因为set(x)要求元素可哈希(实现__hash__方法),而sorted()要求元素可比较(实现富比较方法如__lt__),但原代码的TypeVar("T")没有任何约束,类型检查工具无法确认T同时满足这两个条件。
下面提供两种可行的解决方案:
方法1:用交集类型直接约束TypeVar
从Python 3.10开始支持显式交集类型(&),结合TypeVar的bound参数,直接约束T同时实现Hashable和SupportsRichComparison:
from typing import TypeVar, Hashable, SupportsRichComparison T = TypeVar("T", bound=Hashable & SupportsRichComparison) def f(x: list[T]) -> list[T]: return sorted(set(x))
如果使用Python 3.9及更早版本,添加from __future__ import annotations即可让类型检查工具识别交集语法。
方法2:自定义复合Protocol
如果需要更清晰的语义定义,或者兼容旧版类型检查逻辑,可以自定义一个同时继承Hashable和SupportsRichComparison的协议:
from typing import TypeVar, Protocol, Hashable, SupportsRichComparison class HashableAndComparable(Hashable, SupportsRichComparison, Protocol): pass T = TypeVar("T", bound=HashableAndComparable) def f(x: list[T]) -> list[T]: return sorted(set(x))
这个自定义协议可以直观表达"同时可哈希、可比较"的约束,后续扩展也更灵活。
两种方案都能通过mypy和pyright的类型校验,满足你的需求。
内容的提问来源于stack exchange,提问作者obk
相关产品推荐
相关产品推荐

