Skip to content

Commit 7c3e2db

Browse files
authored
[ty] Fix enum class container assignability (#27318)
## Summary Fixes astral-sh/ty#4114. Enum classes were incorrectly rejected as `Container[T]` even though `EnumMeta.__contains__` accepts `object`. The underlying issue was that concrete class objects and generic aliases were considered assignable to `type[Any]` during eager relation checks, but not while lazily solving explicitly annotated metaclass-receiver constraints. This produced an unsatisfiable hidden constraint on an otherwise correctly bound `__contains__` method. Make class literals and generic aliases consistently assignable to gradual `type[...]` targets in both eager and lazy assignability checks, while preserving stricter subtyping and incompatible protocol signatures. ## Test plan - Added enum mdtests covering `Enum`, `IntEnum`, and `StrEnum`, including unparameterized containers, `Container[Any]`, `Container[object]`, enum-member and unrelated-element container types, and iterable, reversible, and collection protocols. - Added protocol mdtests covering explicitly typed metaclass receivers, conflicting class-level special methods, structural membership protocols, and rejection of incompatible membership parameters and return types. - Verified the original issue reproducer on Python 3.11 through 3.14.
1 parent d5ef97f commit 7c3e2db

3 files changed

Lines changed: 114 additions & 2 deletions

File tree

‎crates/ty_python_semantic/resources/mdtest/enums.md‎

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1995,6 +1995,49 @@ reveal_type(Answer.name) # revealed: Literal[Answer.name]
19951995
reveal_type(Answer.value) # revealed: Literal[Answer.value]
19961996
```
19971997

1998+
## Enum classes as collection protocols
1999+
2000+
An enum class is a container because `EnumMeta.__contains__` accepts any object. Consequently, the
2001+
class satisfies `Container[T]` for every `T`, including types unrelated to its members. Its
2002+
metaclass also provides the iteration, reversal, and length methods required by the corresponding
2003+
collection protocols.
2004+
2005+
```toml
2006+
[environment]
2007+
python-version = "3.12"
2008+
```
2009+
2010+
```py
2011+
from collections.abc import Collection, Container, Iterable, Reversible
2012+
from enum import Enum, IntEnum, StrEnum, auto
2013+
from typing import Any
2014+
2015+
class Color(Enum):
2016+
RED = auto()
2017+
2018+
unparameterized_container: Container = Color
2019+
any_container: Container[Any] = Color
2020+
object_container: Container[object] = Color
2021+
member_container: Container[Color] = Color
2022+
integer_container: Container[int] = Color
2023+
string_container: Container[str] = Color
2024+
iterable: Iterable[Color] = Color
2025+
reversible: Reversible[Color] = Color
2026+
collection: Collection[Color] = Color
2027+
2028+
class Number(IntEnum):
2029+
ONE = 1
2030+
2031+
integer_enum_container: Container[int] = Number
2032+
integer_enum_iterable: Iterable[int] = Number
2033+
2034+
class Word(StrEnum):
2035+
HELLO = "hello"
2036+
2037+
string_enum_container: Container[str] = Word
2038+
string_enum_iterable: Iterable[str] = Word
2039+
```
2040+
19982041
## Iterating over enum members
19992042

20002043
```py

‎crates/ty_python_semantic/resources/mdtest/protocols.md‎

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4291,6 +4291,75 @@ class Custom:
42914291
static_assert(is_assignable_to(TypeOf[Custom], CustomProtocol))
42924292
```
42934293

4294+
## Class objects with explicitly typed special-method receivers
4295+
4296+
A special method defined on a metaclass receives the class object, not an instance of that class. An
4297+
explicitly annotated metaclass receiver must therefore be checked against the class object when
4298+
matching a collection protocol. Special-method lookup must also ignore conflicting methods defined
4299+
on the class itself.
4300+
4301+
```py
4302+
from collections.abc import Collection, Container, Iterable, Iterator, Reversible
4303+
from typing import Any, Protocol
4304+
from ty_extensions import static_assert
4305+
from ty_extensions._internal import TypeOf, is_assignable_to, is_subtype_of
4306+
4307+
class Membership(Protocol):
4308+
def __contains__(self, value: int, /) -> bool: ...
4309+
4310+
class CollectionMeta(type):
4311+
def __contains__(self: type[Any], value: object, /) -> bool:
4312+
return True
4313+
4314+
def __iter__(self: type[Any]) -> Iterator[int]:
4315+
return iter((1,))
4316+
4317+
def __reversed__(self: type[Any]) -> Iterator[int]:
4318+
return iter((1,))
4319+
4320+
def __len__(self: type[Any]) -> int:
4321+
return 1
4322+
4323+
class ClassCollection(metaclass=CollectionMeta):
4324+
def __contains__(self, value: str, /) -> bool:
4325+
return True
4326+
4327+
def __iter__(self) -> Iterator[str]:
4328+
return iter(("member",))
4329+
4330+
def __reversed__(self) -> Iterator[str]:
4331+
return iter(("member",))
4332+
4333+
static_assert(is_assignable_to(TypeOf[ClassCollection], Membership))
4334+
static_assert(is_assignable_to(TypeOf[ClassCollection], Container[int]))
4335+
static_assert(is_assignable_to(TypeOf[ClassCollection], Container[str]))
4336+
static_assert(is_subtype_of(TypeOf[ClassCollection], Container[int]))
4337+
static_assert(is_assignable_to(TypeOf[ClassCollection], Iterable[int]))
4338+
static_assert(is_assignable_to(TypeOf[ClassCollection], Reversible[int]))
4339+
static_assert(is_assignable_to(TypeOf[ClassCollection], Collection[int]))
4340+
```
4341+
4342+
The explicit receiver must not hide an incompatible membership parameter or return type.
4343+
4344+
```py
4345+
class StringMembershipMeta(type):
4346+
def __contains__(self: type[Any], value: str, /) -> bool:
4347+
return True
4348+
4349+
class StringMembership(metaclass=StringMembershipMeta):
4350+
pass
4351+
4352+
class NonBooleanMembershipMeta(type):
4353+
def __contains__(self: type[Any], value: object, /) -> int:
4354+
return 1
4355+
4356+
class NonBooleanMembership(metaclass=NonBooleanMembershipMeta):
4357+
pass
4358+
4359+
static_assert(not is_assignable_to(TypeOf[StringMembership], Container[int]))
4360+
static_assert(not is_assignable_to(TypeOf[NonBooleanMembership], Container[int]))
4361+
```
4362+
42944363
## Subtyping of protocols with `@classmethod` or `@staticmethod` members
42954364

42964365
The typing spec states that protocols may have `@classmethod` or `@staticmethod` method members.

‎crates/ty_python_semantic/src/types/relation.rs‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2259,7 +2259,7 @@ impl<'a, 'c, 'db> TypeRelationChecker<'a, 'c, 'db> {
22592259
.unwrap_or_else(|| {
22602260
ConstraintSet::from_bool(
22612261
self.constraints,
2262-
self.is_eager_assignability(),
2262+
self.relation.is_assignability(),
22632263
)
22642264
}),
22652265
}
@@ -2300,7 +2300,7 @@ impl<'a, 'c, 'db> TypeRelationChecker<'a, 'c, 'db> {
23002300
.unwrap_or_else(|| {
23012301
ConstraintSet::from_bool(
23022302
self.constraints,
2303-
self.is_eager_assignability(),
2303+
self.relation.is_assignability(),
23042304
)
23052305
}),
23062306
}

0 commit comments

Comments
 (0)