From 5a3deee353d864f5b7a303768940d7573bbd4ac2 Mon Sep 17 00:00:00 2001 From: Alex Waygood Date: Mon, 12 Jan 2026 12:26:47 +0000 Subject: [PATCH] [ty] Fix incorrect narrowing for `if type(x) == y` (#22531) --- crates/ty_python_semantic/resources/mdtest/narrow/type.md | 7 ++++++- crates/ty_python_semantic/src/types/narrow.rs | 8 ++++---- 2 files changed, 10 insertions(+), 5 deletions(-) diff --git a/crates/ty_python_semantic/resources/mdtest/narrow/type.md b/crates/ty_python_semantic/resources/mdtest/narrow/type.md index de962d2075..cad02f63cd 100644 --- a/crates/ty_python_semantic/resources/mdtest/narrow/type.md +++ b/crates/ty_python_semantic/resources/mdtest/narrow/type.md @@ -134,12 +134,17 @@ class IsEqualToEverything(type): class A(metaclass=IsEqualToEverything): ... class B(metaclass=IsEqualToEverything): ... -def _(x: A | B): +def _(x: A | B, y: object): if type(x) == A: reveal_type(x) # revealed: A | B if type(x) != A: reveal_type(x) # revealed: A | B + + if type(y) == bool: + reveal_type(y) # revealed: object + else: + reveal_type(y) # revealed: object ``` ## No narrowing for custom `type` callable diff --git a/crates/ty_python_semantic/src/types/narrow.rs b/crates/ty_python_semantic/src/types/narrow.rs index 31d16b4500..e939c59826 100644 --- a/crates/ty_python_semantic/src/types/narrow.rs +++ b/crates/ty_python_semantic/src/types/narrow.rs @@ -1220,10 +1220,10 @@ impl<'db, 'ast> NarrowingConstraintsBuilder<'db, 'ast> { _ => continue, }; - let is_positive = if is_positive { - op == &ast::CmpOp::Is - } else { - op == &ast::CmpOp::IsNot + let is_positive = match op { + ast::CmpOp::Is => is_positive, + ast::CmpOp::IsNot => !is_positive, + _ => continue, }; // `else`-branch narrowing for `if type(x) is Y` can only be done