Skip to content

Commit 0cb0e2a

Browse files
committed
Add narrowing for enum with type()
1 parent 78d8780 commit 0cb0e2a

3 files changed

Lines changed: 29 additions & 0 deletions

File tree

‎crates/zuban_python/src/file/flow_analysis.rs‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5521,6 +5521,14 @@ fn check_for_comparison_guard(
55215521
if !truthy.is_simple_sub_type_of(i_s, &inf_t).bool() {
55225522
truthy = Type::Never(NeverCause::Other);
55235523
}
5524+
if inf_t
5525+
.iter_with_unpacked_unions(i_s.db)
5526+
.any(|t| matches!(t, Type::EnumMember(_)))
5527+
{
5528+
// TODO enum members should be narrowed, but otherwise have weird behavior if
5529+
// we don't special case them.
5530+
return None;
5531+
}
55245532
Some(FramesWithParentUnions {
55255533
truthy: Frame::from_type(key.clone(), truthy),
55265534
falsey: match is_final {

‎crates/zuban_python/src/type_/mod.rs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -719,6 +719,7 @@ impl Type {
719719
match self {
720720
Type::Class(c) => c.class(db).use_cached_class_infos(db).is_final,
721721
Type::Dataclass(d) => d.class(db).use_cached_class_infos(db).is_final,
722+
Type::Enum(_) | Type::EnumMember(_) => true, // Enums are always final
722723
_ => false,
723724
}
724725
}

‎crates/zuban_python/tests/mypylike/tests/narrowing.test‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -151,6 +151,26 @@ def f(x: D | None):
151151
else:
152152
assert_type(x, None)
153153

154+
[case narrowing_type_of_enum]
155+
# flags: --warn-unreachable
156+
from typing import final, assert_type, Literal
157+
from enum import Enum
158+
159+
class E(Enum):
160+
X = 1
161+
Y = 2
162+
163+
def f(x: E | None, y: Literal[E.X] | None):
164+
if type(x) is E:
165+
assert_type(x, E)
166+
else:
167+
assert_type(x, None)
168+
169+
if type(y) is E:
170+
assert_type(y, Literal[E.X] | None) # TODO enum members are a bit hard to narrow
171+
else:
172+
assert_type(y, Literal[E.X] | None)
173+
154174
[case avoid_narrowing_of_len_with_big_unpack]
155175
from typing import Tuple
156176
from typing_extensions import Unpack

0 commit comments

Comments
 (0)