Skip to content

Commit fb2f921

Browse files
authored
[ty] Fix narrowing of strings and integers compared with enum members (#29743)
A plain string can compare equal to a `StrEnum` member. Previously, `if value == Color.RED` narrowed a `str` to the enum and allowed `value.name`, even when `value` was the string `"red"`. The same problem affected integers compared with `IntEnum` members. Keep the matching `str` or `int` type in equality checks, tuple membership tests, and `match` value patterns. A value already known to belong to the enum can still narrow to a specific member. Closes astral-sh/ty#4827 ## Test plan Ran the reproducer with Python 3.13. The plain values `"a"` and `1` entered all three kinds of branches, and `.name` on the string raised `AttributeError`. With both default and strict equality settings, ty now reveals `str` and `int` in those branches and reports the invalid `.name` access. ## Ecosystem report Apprise loses a false warning about converting a plain string to an enum member. pip gains an assignment error where typeshed requires `VerifyMode` and CPython also accepts the plain integer `2`. Both changes are expected. [Analyzed head `e0388646c9f0d4ac09dfea732b05ca2d84839950`](e038864) · [Full ecosystem report](#29743 (comment))
1 parent d181287 commit fb2f921

4 files changed

Lines changed: 60 additions & 10 deletions

File tree

‎crates/ty_python_semantic/resources/mdtest/narrow/conditionals/eq.md‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -864,6 +864,29 @@ def loop_back():
864864
value = Integer.Y
865865
```
866866

867+
The comparison narrows a `str | int` to the matching builtin type. A plain string can equal
868+
`String.X` and reach the `.name` access.
869+
870+
```py
871+
def compare_with_enum_member(value: str | int):
872+
if value == String.X:
873+
reveal_type(value) # revealed: str
874+
value.name # error: [unresolved-attribute]
875+
876+
if Integer.X == value:
877+
reveal_type(value) # revealed: int
878+
```
879+
880+
Members of other `IntEnum` classes can also compare equal to `Integer.X`.
881+
882+
```py
883+
def compare_int_enums(value: IntEnum):
884+
if value != Integer.X:
885+
reveal_type(value) # revealed: IntEnum & ~Literal[Integer.X]
886+
else:
887+
reveal_type(value) # revealed: IntEnum
888+
```
889+
867890
A custom `__new__` can replace the value declared in an `IntEnum` class body. We can still narrow
868891
the members of `Foo`, whose runtime values are known, but must preserve all of `Shifted` because its
869892
members' runtime values cannot be determined statically:

‎crates/ty_python_semantic/resources/mdtest/narrow/conditionals/in.md‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1442,6 +1442,19 @@ def _(colors: list[Color]):
14421442
reveal_type(inline) # revealed: list[Color]
14431443
```
14441444

1445+
Membership succeeds for the plain integer `1` as well as for the enum member `Code.OK`.
1446+
1447+
```py
1448+
from enum import IntEnum
1449+
1450+
class Code(IntEnum):
1451+
OK = 1
1452+
1453+
def check_membership(value: int):
1454+
if value in (Code.OK,):
1455+
reveal_type(value) # revealed: int
1456+
```
1457+
14451458
An enum that can have additional runtime members can still be narrowed by a membership test against
14461459
an explicit member. The other branch excludes that member without assuming that the declared members
14471460
are exhaustive.

‎crates/ty_python_semantic/resources/mdtest/narrow/match.md‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4032,6 +4032,12 @@ class Color(StrEnum):
40324032
GREEN = "g"
40334033
BLUE = "b"
40344034

4035+
def match_string(value: str):
4036+
match value:
4037+
case Color.GREEN as captured:
4038+
reveal_type(value) # revealed: str
4039+
reveal_type(captured) # revealed: str
4040+
40354041
def test_literal_as_enum(x: Literal["g"]) -> None:
40364042
match x:
40374043
case Color.RED:

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

Lines changed: 18 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1530,7 +1530,20 @@ fn compare_literal_to_other<'db>(
15301530
};
15311531
let condition_expects_equality = operator.condition_expects_equality(branch);
15321532

1533-
// Treat broad builtin types as if only the literal itself can compare equal. This is
1533+
let literal_constraint = || {
1534+
if !condition_expects_equality {
1535+
ComparisonResult::CanNarrow(literal_type.negate(db, env))
1536+
} else if matches!(literal, LiteralValueTypeKind::Enum(_))
1537+
&& literal_semantics != KnownComparisonSemantics::Object
1538+
{
1539+
// A plain string can compare equal to a `StrEnum` member.
1540+
ComparisonResult::Ambiguous
1541+
} else {
1542+
ComparisonResult::CanNarrow(literal_type)
1543+
}
1544+
};
1545+
1546+
// Treat broad builtin types as if only the builtin literal itself can compare equal. This is
15341547
// intentionally unsafe: subclasses, including `bool` for `int`, can compare equal without
15351548
// inhabiting the literal type. Explicitly typed subclasses do not take this path.
15361549
if evaluator.soundness_policy.allow_unsafe_equality
@@ -1539,7 +1552,7 @@ fn compare_literal_to_other<'db>(
15391552
&& let Some(other_semantics) = unsafe_narrowable_builtin_semantics(db, other)
15401553
{
15411554
return if literal_semantics == other_semantics {
1542-
ComparisonResult::CanNarrow(literal_type)
1555+
literal_constraint()
15431556
} else {
15441557
operator.result_from_equality(false)
15451558
};
@@ -1564,17 +1577,12 @@ fn compare_literal_to_other<'db>(
15641577
if literal_operand == LiteralOperand::Other
15651578
&& !other.is_disjoint_from(db, env, literal_type) =>
15661579
{
1567-
ComparisonResult::CanNarrow(literal_type.negate_if(
1568-
db,
1569-
env,
1570-
!condition_expects_equality,
1571-
))
1580+
literal_constraint()
15721581
}
1573-
Some(_) => ComparisonResult::Ambiguous,
15741582
None if literal_operand == LiteralOperand::Other && !condition_expects_equality => {
1575-
ComparisonResult::CanNarrow(literal_type.negate(db, env))
1583+
literal_constraint()
15761584
}
1577-
None => ComparisonResult::Ambiguous,
1585+
_ => ComparisonResult::Ambiguous,
15781586
}
15791587
}
15801588

0 commit comments

Comments
 (0)