Ruff 类型检查器(ty)如何为 `@functools.total_ordering` 合成比较方法:mdtest 行为规范与源码实现解析

原创2026-09-09 13:05:591,693 阅读
文章标签:开发工具代码质量Lint格式化静态分析CLI

Ruff 类型检查器(ty)如何为 @functools.total_ordering 合成比较方法:mdtest 行为规范与源码实现解析

导读:本文以仓库内类型检查器(ty)的 mdtest 行为测试文档 crates/ty_python_semantic/resources/mdtest/decorators/total_ordering.md 为骨架,系统梳理 @functools.total_ordering 装饰器在静态类型推断中的完整语义:比较方法合成规则、root 方法优先级、签名推导、重载保留、继承与动态类(type())支持,并结合 ty_python_semantic crate 的源码逐条印证实现原理。读完你不仅能理解该测试的全部断言行为,还能定位到合成逻辑、诊断上报与装饰器识别在仓库中的具体实现位置。

背景:这份 mdtest 文档在仓库中的角色

total_ordering.md 是 Ruff 仓库中类型检查器 ty 的 mdtest 行为规范文档,存放于 crates/ty_python_semantic/resources/mdtest/decorators/ 目录。这类文档以 Markdown 内嵌 Python 代码的方式,通过 reveal_type(...)(期望推断出的类型)与 # error: [...](期望诊断错误码)两条机制,把类型检查器的行为固化为可执行断言。

文档的核心主题是:当类使用 @functools.total_ordering 装饰器时,ty 类型检查器如何像 Python 运行时一样,基于用户定义的单个比较方法(如 __lt__),自动"合成"出其余比较方法(__le__、__gt__、__ge__)的类型签名,并给出正确的推断结果或诊断信息。

@total_ordering 本身的行为很直观:它要求类至少定义一个排序方法,运行时据此生成其余方法。但"静态类型推断"要还原这套逻辑,需要解决一系列边界问题:方法签名怎么继承、重载怎么保留、继承来的方法算不算数、动态命名空间怎么办、缺失方法时报什么错——这正是本文档逐节覆盖的内容。

基本用法:从单个 __lt__ 合成全套比较方法

文档开头给出了最基础也最核心的语义:当一个类定义了 __eq__ 与 __lt__ 时,装饰器自动合成 __le__、__gt__、__ge__:

from functools import total_ordering

@total_ordering
class Student:
    def __init__(self, grade: int):
        self.grade = grade

    def __eq__(self, other: object) -> bool:
        if not isinstance(other, Student):
            return NotImplemented
        return self.grade == other.grade

    def __lt__(self, other: "Student") -> bool:
        return self.grade < other.grade

s1 = Student(85)
s2 = Student(90)

# 用户自定义的比较方法工作正常
reveal_type(s1 == s2)  # revealed: bool
reveal_type(s1 < s2)   # revealed: bool

# 合成的比较方法可用
reveal_type(s1 <= s2)  # revealed: bool
reveal_type(s1 > s2)   # revealed: bool
reveal_type(s1 >= s2)  # revealed: bool

这里有两个可验证的推断事实:== 与 < 返回用户声明的方法返回类型 bool;而 <=、>、>= 即便在源码里不存在,也被推断为 bool——说明类型检查器确实"看见了"装饰器合成的方法。

源码印证:合成发生在 own_synthesized_member

从源码看,合成逻辑位于 crates/ty_python_semantic/src/types/class/static_literal.rs 的 own_synthesized_member(约 L1646-L1700)。该函数处理 @functools.total_ordering 时满足以下条件才合成:

  1. 类带有 total_ordering 标记(即被装饰器修饰);
  2. 请求的方法名属于 __lt__、__le__、__gt__、__ge__ 之一;
  3. 该方法尚未在 MRO 中显式定义(显式定义的不覆盖);
  4. 类在 MRO(排除 object)中至少存在一个排序方法(has_ordering_method_in_mro);
  5. 能取得 root 排序方法并 upcast 为可调用类型。

满足条件后,合成方法会克隆 root 方法的参数列表,并把返回类型与 bool 取并集(UnionType::from_two_elements),原因在后文"非 bool 返回类型"一节详细说明。

与类保持装饰器叠加:元数据穿透

实际代码中 @total_ordering 常常与其他装饰器一起使用。文档断言:当一个显式标注返回类型且保持类身份(class-preserving)的装饰器位于 @total_ordering 之下时,@total_ordering 的元数据依然生效:

from functools import total_ordering
from typing import TypeVar

T = TypeVar("T", bound=object)

def identity(cls: type[T]) -> type[T]:
    return cls

@total_ordering
@identity
class OrderedIdentity:
    def __eq__(self, other: object) -> bool:
        return isinstance(other, OrderedIdentity)

    def __lt__(self, other: "OrderedIdentity") -> bool:
        return True

left = OrderedIdentity()
right = OrderedIdentity()

reveal_type(left <= right)  # revealed: bool
reveal_type(left >= right)  # revealed: bool

即 <= 与 >= 依然被合成。

源码印证:装饰器识别在 class.rs

@total_ordering 的标记是如何进入类字面量的?在 crates/ty_python_semantic/src/types/infer/builder/class.rs(约 L186-L192)中,类型检查器遍历装饰器列表,通过 function.is_known(db, KnownFunction::TotalOrdering) 识别出 functools.total_ordering,随后把 total_ordering = true 写入 StaticClassLiteral。而 StaticClassLiteral 上的 total_ordering 字段(static_literal.rs L96-L98,注释为 "Whether this class is decorated with @functools.total_ordering")是后续一切合成与校验的总开关。函数级已知标识 KnownFunction::TotalOrdering 的定义与判定见 crates/ty_python_semantic/src/types/function.rs(L2321 枚举项、L2445 处要求 module.is_functools())。

签名推导:从源排序方法继承参数类型

当源排序方法的 other 参数接受更宽的类型(比如 object)时,合成方法的签名必须保持一致,否则会出现"合成的 <= 无法与 int 比较"的误报。文档中的 Comparable 示例演示了这一点:

from functools import total_ordering

@total_ordering
class Comparable:
    def __init__(self, value: int):
        self.value = value

    def __eq__(self, other: object) -> bool:
        if isinstance(other, Comparable):
            return self.value == other.value
        if isinstance(other, int):
            return self.value == other
        return NotImplemented

    def __lt__(self, other: object) -> bool:
        if isinstance(other, Comparable):
            return self.value < other.value
        if isinstance(other, int):
            return self.value < other
        return NotImplemented

a = Comparable(10)
b = Comparable(20)

reveal_type(a <= b)   # revealed: bool
reveal_type(a >= b)   # revealed: bool
# 因为 __lt__ 接受 object,与 int 的比较也成立
reveal_type(a <= 15)  # revealed: bool
reveal_type(a >= 5)   # revealed: bool

这与源码实现完全吻合:own_synthesized_member 中 Signature::new_generic 直接复用 root_method_ty 的 parameters(),即参数签名一字不差地继承自 root 排序方法,仅返回类型被改造为"原返回类型 ∪ bool"。

Root 方法选择:__lt__ > __le__ > __gt__ > __ge__

当类定义了多个签名不同的排序方法时,装饰器需要一个"根"方法作为合成基准。文档明确给出优先级顺序:__lt__ > __le__ > __gt__ > __ge__,并且已显式定义的方法不会被覆盖:

from functools import total_ordering

@total_ordering
class MultiSig:
    def __init__(self, value: int):
        self.value = value

    def __eq__(self, other: object) -> bool:
        return True

    # __lt__ 接受 object(最高优先级,作为 root)
    def __lt__(self, other: object) -> bool:
        return True

    # __gt__ 只接受 MultiSig(不被装饰器覆盖)
    def __gt__(self, other: "MultiSig") -> bool:
        return True

a = MultiSig(10)
b = MultiSig(20)

# __le__ 与 __ge__ 使用 __lt__ 的签名(接受 object)
reveal_type(a <= b)    # revealed: bool
reveal_type(a <= 15)   # revealed: bool
reveal_type(a >= b)    # revealed: bool
reveal_type(a >= 15)   # revealed: bool

# __gt__ 保留原始签名(只接受 MultiSig)
reveal_type(a > b)     # revealed: bool
a > 15  # error: [unsupported-operator]

注意最后一个断言的戏剧性:a <= 15 合法(来自合成的 __le__,继承 __lt__ 的宽签名),而 a > 15 报 unsupported-operator 错误(因为 __gt__ 是显式定义的,保留窄签名)。这验证了"显式定义优先、合成只补缺"的设计。

源码印证:total_ordering_root_method 与 MRO 遍历

total_ordering_root_method(static_literal.rs L309-L357)正是优先级规则的实现:内部定义 const ORDERING_METHODS: [&str; 4] = ["__lt__", "__le__", "__gt__", "__ge__"],按此顺序外层遍历;对每个方法名,再沿 iter_mro 遍历 MRO(跳过 object),命中即返回。因此它天然满足两点:优先级固定、无论方法定义在本地还是继承自父类均一视同仁。同时,own_synthesized_member 中"不合成 MRO 已存在的方法"的条件(遍历 MRO 检查同名方法是否存在)保证了显式定义不被覆盖。而 has_own_ordering_method(L282-L288)与 has_own_comparison_methods(L290-L296)分别提供"是否定义了任意一个/全部四个排序方法"的辅助判定。

重载的排序方法:保留全部 overload

如果 root 排序方法使用了 @overload,合成方法必须保留全部重载签名。文档用 Flexible 类验证:

from functools import total_ordering
from typing import overload

@total_ordering
class Flexible:
    def __init__(self, value: int):
        self.value = value

    def __eq__(self, other: object) -> bool:
        return True

    @overload
    def __lt__(self, other: "Flexible") -> bool: ...
    @overload
    def __lt__(self, other: int) -> bool: ...
    def __lt__(self, other: "Flexible | int") -> bool:
        if isinstance(other, Flexible):
            return self.value < other.value
        return self.value < other

a = Flexible(10)
b = Flexible(20)

# 合成的 __le__ 保留 __lt__ 的重载
reveal_type(a <= b)   # revealed: bool
reveal_type(a <= 15)  # revealed: bool

# 合成的 __ge__ 同样保留重载
reveal_type(a >= b)   # revealed: bool
reveal_type(a >= 15)  # revealed: bool

# 与不支持的类型比较仍应报错
a <= "string"  # error: [unsupported-operator]

源码印证:CallableSignature::from_overloads

源码中 own_synthesized_member 使用 CallableSignature::from_overloads(callable.signatures(db).iter().map(...)) 逐个转换 root 方法的所有签名,从而把重载集合整体搬到合成方法上(static_literal.rs L1680-L1696)。这也是"a <= 15 合法、a <= "string" 报错"的底层原因:重载集合中只有 Flexible 与 int 两个分支。

__gt__ 作为 root:对称合成

优先级并不总是从 __lt__ 出发。当类只定义 __eq__ 与 __gt__ 时,装饰器以 __gt__ 为 root 合成 __lt__、__le__、__ge__:

from functools import total_ordering

@total_ordering
class Priority:
    def __init__(self, level: int):
        self.level = level

    def __eq__(self, other: object) -> bool:
        if not isinstance(other, Priority):
            return NotImplemented
        return self.level == other.level

    def __gt__(self, other: "Priority") -> bool:
        return self.level > other.level

p1 = Priority(1)
p2 = Priority(2)

reveal_type(p1 == p2)  # revealed: bool(用户定义)
reveal_type(p1 > p2)   # revealed: bool(用户定义)
reveal_type(p1 < p2)   # revealed: bool(合成)
reveal_type(p1 <= p2)  # revealed: bool(合成)
reveal_type(p1 >= p2)  # revealed: bool(合成)

继承场景一:__eq__ 从 object 继承

文档强调 __eq__ 是可选的——它可以继承自 object,类只需定义一个排序方法即可触发合成:

from functools import total_ordering

@total_ordering
class Score:
    def __init__(self, value: int):
        self.value = value

    def __lt__(self, other: "Score") -> bool:
        return self.value < other.value

s1 = Score(85)
s2 = Score(90)

reveal_type(s1 == s2)  # revealed: bool(继承自 object)
reveal_type(s1 <= s2)  # revealed: bool
reveal_type(s1 > s2)   # revealed: bool
reveal_type(s1 >= s2)  # revealed: bool

继承场景二:排序方法来自父类

装饰器同样支持排序方法继承自父类的情形:

from functools import total_ordering

class Base:
    def __lt__(self, other: "Base") -> bool:
        return True

@total_ordering
class Child(Base):
    def __eq__(self, other: object) -> bool:
        if not isinstance(other, Child):
            return NotImplemented
        return True

c1 = Child()
c2 = Child()

# 即使 __lt__ 是继承来的,合成方法依然生效
reveal_type(c1 <= c2)  # revealed: bool
reveal_type(c1 > c2)   # revealed: bool
reveal_type(c1 >= c2)  # revealed: bool

继承场景三:优先级不受"本地/继承"影响

优先级规则的一个重要推论是:无论方法定义在本地还是继承自父类,__lt__ 的优先级都高于 __gt__。文档给出了一个反直觉的例子——本地定义了 __gt__,但继承的 __lt__ 才是 root:

from functools import total_ordering
from typing import Literal

class Base:
    def __lt__(self, other: "Base") -> Literal[True]:
        return True

@total_ordering
class Child(Base):
    # __gt__ 定义在本地,但 __lt__(继承)优先
    def __gt__(self, other: "Child") -> Literal[False]:
        return False

c1 = Child()
c2 = Child()

reveal_type(c1 < c2)   # revealed: Literal[True]  (继承自 Base)
reveal_type(c1 > c2)   # revealed: Literal[False] (Child 本地定义)
# __le__ 与 __ge__ 基于 __lt__ 合成,即使 __gt__ 定义在类自身
reveal_type(c1 <= c2)  # revealed: bool
reveal_type(c1 >= c2)  # revealed: bool

这里用 Literal[True]/Literal[False] 精确区分了方法来源:< 返回 Literal[True] 证明它来自 Base.__lt__;> 返回 Literal[False] 证明它是 Child.__gt__ 原样保留。而合成的 <=/>= 返回普通 bool——合成方法的返回类型是"root 返回类型 ∪ bool"(Literal[True] | bool 化简为 bool)。

显式定义的方法不被覆盖

承接上一点,文档用更窄的返回类型验证"显式定义优先"原则:

from functools import total_ordering
from typing import Literal

@total_ordering
class Temperature:
    def __init__(self, celsius: float):
        self.celsius = celsius

    def __lt__(self, other: "Temperature") -> Literal[True]:
        return True

    def __gt__(self, other: "Temperature") -> Literal[True]:
        return True

t1 = Temperature(20.0)
t2 = Temperature(25.0)

# 用户定义的方法保留其返回类型
reveal_type(t1 < t2)   # revealed: Literal[True]
reveal_type(t1 > t2)   # revealed: Literal[True]

# 合成方法的返回类型为 bool
reveal_type(t1 <= t2)  # revealed: bool
reveal_type(t1 >= t2)  # revealed: bool

__le__、__ge__ 的返回类型是 Literal[True] | bool 并集化简后的 bool,而显式的 __lt__、__gt__ 精确保持 Literal[True]——两者形成鲜明对比,正是 own_synthesized_member 中"仅在 MRO 未定义该方法时才合成"逻辑的直接体现。

与 @dataclass 组合使用

@total_ordering 与 @dataclass 可以安全叠加。dataclass 会合成 __eq__,用户再定义 __lt__,其余方法由 total_ordering 补齐:

from dataclasses import dataclass
from functools import total_ordering

@total_ordering
@dataclass
class Point:
    x: int
    y: int

    def __lt__(self, other: "Point") -> bool:
        return (self.x, self.y) < (other.x, other.y)

p1 = Point(1, 2)
p2 = Point(3, 4)

reveal_type(p1 == p2)  # revealed: bool(dataclass 合成的 __eq__)
reveal_type(p1 < p2)   # revealed: bool(用户定义)
reveal_type(p1 <= p2)  # revealed: bool(total_ordering 合成)
reveal_type(p1 > p2)   # revealed: bool(total_ordering 合成)
reveal_type(p1 >= p2)  # revealed: bool(total_ordering 合成)

这与源码中 own_synthesized_member 的定位一致:它是 dataclass、NamedTuple、total_ordering 等多条合成路径的公共入口(函数注释 "Returns the type of a synthesized dataclass member like __init__ or __lt__, or a synthesized __new__ method for a NamedTuple",见 static_literal.rs L1644-L1653),total_ordering 分支只是其中一条。

缺失排序方法:invalid-total-ordering 诊断

如果类带了 @total_ordering 却连一个排序方法都没定义(自身与父类都没有),类型检查器会在装饰器所在位置上报 invalid-total-ordering 诊断,且由于没有合成任何方法,比较运算符本身也报 unsupported-operator:

from functools import total_ordering

@total_ordering  # error: [invalid-total-ordering]
class NoOrdering:
    def __eq__(self, other: object) -> bool:
        return True

n1 = NoOrdering()
n2 = NoOrdering()

n1 <= n2  # error: [unsupported-operator]
n1 >= n2  # error: [unsupported-operator]

这与 Python 运行时行为一致:@total_ordering 要求至少一个排序方法,否则抛出 ValueError。

源码印证:诊断上报链路

诊断上报发生在 crates/ty_python_semantic/src/types/infer/builder/post_inference/static_class.rs(约 L643-L653):当 class.total_ordering(db) 为真且 !class.has_ordering_method_in_mro(db, None) 时,在 decorator_list 中定位到 KnownFunction::TotalOrdering 对应的装饰器节点,调用 report_invalid_total_ordering 上报。诊断的规则文档位于 crates/ty_python_semantic/resources/lint_docs/invalid-total-ordering.md,其中明确说明:未定义排序方法时 Python 会在运行时抛出 ValueError,并给出修正示例(补上 __lt__)。诊断注册(report_invalid_total_ordering 等导入)见同一文件的 L39。规则汇总可查阅 crates/ty/docs/rules.md。

没有装饰器时:不合成

对照实验:不加 @total_ordering 时,只定义 __lt__ 的类不会有 __le__、__ge__。这里还揭示了一个 Python 语义细节——n1 > n2 之所以可用,是因为 Python 会把 > 反射(reflected)为 n2 < n1:

class NoDecorator:
    def __init__(self, value: int):
        self.value = value

    def __eq__(self, other: object) -> bool:
        if not isinstance(other, NoDecorator):
            return NotImplemented
        return self.value == other.value

    def __lt__(self, other: "NoDecorator") -> bool:
        return self.value < other.value

n1 = NoDecorator(1)
n2 = NoDecorator(2)

reveal_type(n1 == n2)  # revealed: bool
reveal_type(n1 < n2)   # revealed: bool
# n1 > n2 可用是因为 Python 反射为 n2 < n1
reveal_type(n1 > n2)   # revealed: bool

n1 <= n2  # error: [unsupported-operator]
n1 >= n2  # error: [unsupported-operator]

这从反面说明:total_ordering 分支的合成是有装饰器标记才触发的(self.total_ordering(db) 是 own_synthesized_member 的第一个条件),反射式比较不在该合成机制的覆盖范围内。

非 bool 返回类型:合成方法的类型并集语义

这是文档技术密度最高的部分。@total_ordering 生成的代码形如:

def __le__(self, other):
    return self < other or self == other

因此合成方法的返回类型应该是"root 方法的返回类型 ∪ bool"。文档给出两种情形:

情形一:root 返回 int(bool 是 int 的子类型,并集化简为 int)

from functools import total_ordering

@total_ordering
class IntReturn:
    def __init__(self, value: int):
        self.value = value

    def __eq__(self, other: object) -> bool:
        if not isinstance(other, IntReturn):
            return NotImplemented
        return self.value == other.value

    def __lt__(self, other: "IntReturn") -> int:
        return self.value - other.value

a = IntReturn(10)
b = IntReturn(20)

reveal_type(a < b)   # revealed: int(用户定义)
# int | bool 并集因 bool 是 int 子类型而化简为 int
reveal_type(a <= b)  # revealed: int
reveal_type(a > b)   # revealed: int
reveal_type(a >= b)  # revealed: int

情形二:root 返回 str(bool 不是 str 的子类型,并集被保留)

from functools import total_ordering

@total_ordering
class StrReturn:
    def __init__(self, value: str):
        self.value = value

    def __eq__(self, other: object) -> bool:
        if not isinstance(other, StrReturn):
            return NotImplemented
        return self.value == other.value

    def __lt__(self, other: "StrReturn") -> str:
        return self.value

a = StrReturn("a")
b = StrReturn("b")

reveal_type(a < b)   # revealed: str
reveal_type(a <= b)  # revealed: str | bool
reveal_type(a > b)   # revealed: str | bool
reveal_type(a >= b)  # revealed: str | bool

源码印证:UnionType::from_two_elements

实现位于 own_synthesized_member 的签名转换闭包中(static_literal.rs L1679-L1695):let return_ty = UnionType::from_two_elements(db, env, signature.return_ty, bool_ty);,把每个重载的返回类型与 bool_ty 取并集后重建签名。并集化简(int | bool → int)由类型系统的并集化简规则完成,与文档注释的解释("bool is a subtype of int in Python")一致。

函数调用形式:total_ordering(cls)

装饰器语法 @total_ordering 等价于 total_ordering(cls)。函数调用形式执行同样的校验——无排序方法时报 invalid-total-ordering,有则返回原类类型:

from functools import total_ordering

class NoOrderingMethod:
    def __eq__(self, other: object) -> bool:
        return True

# error: [invalid-total-ordering]
InvalidOrderedClass = total_ordering(NoOrderingMethod)
from functools import total_ordering

class HasOrderingMethod:
    def __eq__(self, other: object) -> bool:
        return True

    def __lt__(self, other: "HasOrderingMethod") -> bool:
        return True

# 无错误(类定义了 __lt__)
ValidOrderedClass = total_ordering(HasOrderingMethod)
reveal_type(ValidOrderedClass)  # revealed: type[HasOrderingMethod]

源码印证:KnownFunction::TotalOrdering 的调用检查

函数调用形式的校验位于 crates/ty_python_semantic/src/types/function.rs(约 L3030-L3050):对 KnownFunction::TotalOrdering,取第一个参数并匹配 Type::ClassLiteral / Type::GenericAlias,随后调用 class.has_ordering_method_in_mro(db) 检查;若缺失则调用 report_invalid_total_ordering_call 上报诊断。注意这里与装饰器形式共享同一个 has_ordering_method_in_mro,因此两类入口的校验口径完全一致。

函数调用形式 + type() 动态类

total_ordering 也可以作用于用 type() 构造的类。只要动态类的命名空间里提供了排序方法,就不会报错:

from functools import total_ordering

def lt_impl(self, other) -> bool:
    return True

# 无错误:函数式类在命名空间中定义了 __lt__
ValidFunctional = total_ordering(type("ValidFunctional", (), {"__lt__": lt_impl}))

InvalidFunctionalBase = type("InvalidFunctionalBase", (), {})
# error: [invalid-total-ordering]
InvalidFunctional = total_ordering(InvalidFunctionalBase)

源码印证:动态类字面量的成员查询

total_ordering_root_method 对 ClassLiteral::Dynamic 分支专门处理(static_literal.rs L341-L348):通过 dynamic.own_class_member(db, name) 在动态命名空间中查找排序方法,因此 type(..., {"__lt__": lt_impl}) 能被正确识别。这解释了为什么 ValidFunctional 合法而 InvalidFunctional 报错。

继承自函数式类

当一个类继承自"带排序方法的函数式类"时,@total_ordering 同样能正确检测到继承的方法并完成合成:

from functools import total_ordering

def lt_impl(self, other) -> bool:
    return True

def eq_impl(self, other) -> bool:
    return True

# 带 __lt__ 的函数式基类
OrderedBase = type("OrderedBase", (), {"__lt__": lt_impl})

@total_ordering
class Ordered(OrderedBase):
    def __eq__(self, other: object) -> bool:
        return True

o1 = Ordered()
o2 = Ordered()

reveal_type(o1 < o2)   # revealed: bool(继承的 __lt__)
reveal_type(o1 <= o2)  # revealed: bool(合成)
reveal_type(o1 > o2)   # revealed: bool(合成)
reveal_type(o1 >= o2)  # revealed: bool(合成)

反之,如果动态基类没有任何排序方法,则报错:

from functools import total_ordering

NoOrderBase = type("NoOrderBase", (), {})

@total_ordering  # error: [invalid-total-ordering]
class NoOrder(NoOrderBase):
    def __eq__(self, other: object) -> bool:
        return True

动态命名空间:保守地不报错

最后一个边界情况:当 type() 构造的类带有动态命名空间(来自外部 dict)时,类型检查器无法得知命名空间里是否有排序方法,因此采取保守策略——不报错:

from functools import total_ordering
from typing import Any

def f(ns: dict[str, Any]):
    # 动态命名空间——可能包含排序方法
    DynamicBase = type("DynamicBase", (), ns)

    # 无错误:动态命名空间可能包含 __lt__ 等排序方法
    @total_ordering
    class Ordered(DynamicBase):
        def __eq__(self, other: object) -> bool:
            return True

    # 函数调用形式同样不报错
    OrderedDirect = total_ordering(type("OrderedDirect", (), ns))

这一"宁可信其有"的设计避免了误报:既然无法静态证明排序方法不存在,就信任命名空间可能提供它。这体现了类型检查器在处理动态特性时的务实取舍——把不确定性转化为"允许通过",而不是武断地报错。

小结:一份测试文档映射出的完整实现链路

从这份 mdtest 可以梳理出 ty 对 @functools.total_ordering 的完整支持脉络:

  1. 识别:class.rs 通过 KnownFunction::TotalOrdering 识别装饰器(crates/ty_python_semantic/src/types/infer/builder/class.rs L186-L192),在 StaticClassLiteral 上置位 total_ordering(crates/ty_python_semantic/src/types/class/static_literal.rs L96-L98);
  2. 选根:total_ordering_root_method 按 __lt__ > __le__ > __gt__ > __ge__ 优先级、沿 MRO(排除 object、兼容动态类)选择 root 方法(同文件 L309-L357);
  3. 合成:own_synthesized_member 在"方法尚未定义于 MRO"且"存在 root 方法"时克隆 root 签名、返回类型与 bool 取并集、保留全部重载(同文件 L1646-L1700);
  4. 校验:装饰器形式在 post_inference/static_class.rs L643-L653 检查 MRO 并上报 invalid-total-ordering;函数调用形式在 crates/ty_python_semantic/src/types/function.rs L3030-L3050 走同一 has_ordering_method_in_mro 校验;规则说明见 crates/ty_python_semantic/resources/lint_docs/invalid-total-ordering.md。

对于想要在 Ruff 仓库中继续深入研究的读者,建议从三个入口出发:以本文的 mdtest 文档作为行为总纲(crates/ty_python_semantic/resources/mdtest/decorators/total_ordering.md),以 static_literal.rs 的 own_synthesized_member 与 total_ordering_root_method 作为核心实现,再配合 invalid-total-ordering 规则文档验证诊断语义。@total_ordering 的运行时行为还可对照 typeshed 存根 crates/ty_vendored/vendor/typeshed/stdlib/functools.pyi 理解其函数签名。这三者合在一起,即可完整还原"静态类型检查器如何在不执行代码的前提下,复现一个标准库装饰器的全部语义"。

登录后查看全文
ruff