Skip to content

Add diagnostic warning about unsound subclassing of order=True dataclasses #1681

@AlexWaygood

Description

@AlexWaygood

It's unsound to subclass an order=True dataclass, because the generated comparison methods raise an exception if you try to compare an instance of the subclass with an instance of the superclass:

from dataclasses import dataclass

@dataclass(order=True)
class F:
    x: int

class G(F): ...

G(42) < F(42)  # exception raised here at runtime, but cannot detected by ty

We should detect attempts to subclass order=True dataclasses and warn users about the unsoundness (emitting a diagnostic at the point where G is defined). We could recommend that they use functools.total_ordering instead to generate their comparison methods, as total_ordering doesn't have the same problem.

(One way of describing the problem here is that the design of the stdlib feature violates the Liskov Substitution Principle.)

Metadata

Metadata

Assignees

Labels

dataclassesIssues relating to dataclasses and dataclass_transformruntime semanticsAccurate modeling of how Python's semantics work at runtime

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions