mirror of
https://github.com/astral-sh/ruff.git
synced 2025-10-01 14:21:24 +00:00
[ty] Infer single-valuedness for enums based on int
/str
(#19510)
## Summary We previously didn't recognize `Literal[Color.RED]` as single-valued, if the enum also derived from `str` or `int`: ```py from enum import Enum class Color(str, Enum): RED = "red" GREEN = "green" BLUE = "blue" def _(color: Color): if color == Color.RED: reveal_type(color) # previously: Color, now: Literal[Color.RED] ``` The reason for that was that `int` and `str` have "custom" `__eq__` and `__ne__` implementations that return `bool`. We do not treat enum literals from classes with custom `__eq__` and `__ne__` implementations as single-valued, but of course we know that `int.__eq__` and `str.__eq__` are well-behaved. ## Test Plan New Markdown tests.
This commit is contained in:
parent
cc5885e564
commit
5a55bab3f3
3 changed files with 39 additions and 3 deletions
|
@ -71,6 +71,14 @@ class CustomNeEnum(Enum):
|
|||
def __ne__(self, other: object) -> bool:
|
||||
return False
|
||||
|
||||
class StrEnum(str, Enum):
|
||||
A = "a"
|
||||
B = "b"
|
||||
|
||||
class IntEnum(int, Enum):
|
||||
A = 1
|
||||
B = 2
|
||||
|
||||
static_assert(is_single_valued(Literal[NormalEnum.NO]))
|
||||
static_assert(is_single_valued(Literal[NormalEnum.YES]))
|
||||
static_assert(not is_single_valued(NormalEnum))
|
||||
|
@ -89,4 +97,12 @@ static_assert(not is_single_valued(CustomEqEnum))
|
|||
static_assert(not is_single_valued(Literal[CustomNeEnum.NO]))
|
||||
static_assert(not is_single_valued(Literal[CustomNeEnum.YES]))
|
||||
static_assert(not is_single_valued(CustomNeEnum))
|
||||
|
||||
static_assert(is_single_valued(Literal[StrEnum.A]))
|
||||
static_assert(is_single_valued(Literal[StrEnum.B]))
|
||||
static_assert(not is_single_valued(StrEnum))
|
||||
|
||||
static_assert(is_single_valued(Literal[IntEnum.A]))
|
||||
static_assert(is_single_valued(Literal[IntEnum.B]))
|
||||
static_assert(not is_single_valued(IntEnum))
|
||||
```
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue