From e012150cc34114b14df0bfaaaf659b79c7c1afb4 Mon Sep 17 00:00:00 2001 From: Kyle Into Date: Wed, 18 Nov 2026 20:27:39 -0800 Subject: [PATCH] Assume non-final class instances without `__bool__`/`__len__` are truthy Summary: - What: `as_bool` treats an instance of any class without `__bool__`, `__len__`, `__getattr__`, `__getattribute__` or `__get__` as always truthy, final or not. `x and x.attr` with `x: C | None` becomes `T | None`, not `(C & Falsy) | T | None`. - Why: mypy and pyright make this assumption. Users hit `(Model & Falsy)` on Django models, which are never final. This diff measures the mypy_primer impact; it is not for landing yet. Differential Revision: D133110159 --- pyrefly/lib/alt/expr.rs | 2 +- pyrefly/lib/test/narrow.rs | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/pyrefly/lib/alt/expr.rs b/pyrefly/lib/alt/expr.rs index ffbb971b86..c925c9ad1a 100644 --- a/pyrefly/lib/alt/expr.rs +++ b/pyrefly/lib/alt/expr.rs @@ -2865,7 +2865,7 @@ impl<'ctx, 'answer, Ans: LookupAnswer> AnswersSolver<'ctx, 'answer, Ans> { } } else if let Type::ClassType(cls) = ty { let cls = cls.class_object(); - if !self.is_subclassable(cls) && self.class_instances_always_truthy(cls) { + if self.class_instances_always_truthy(cls) { return Some(true); } } diff --git a/pyrefly/lib/test/narrow.rs b/pyrefly/lib/test/narrow.rs index 6fd0077112..480616837b 100644 --- a/pyrefly/lib/test/narrow.rs +++ b/pyrefly/lib/test/narrow.rs @@ -4880,14 +4880,14 @@ def g(x: A | B | C) -> None: testcase!( test_class_may_be_falsy, r#" -from typing import reveal_type +from typing import assert_type class MyClass: name: str def myfn(x: MyClass | None): - # `x` could be a falsy instance of a subclass of `MyClass` - reveal_type(x and x.name) # E: (MyClass & Falsy) | str | None + # Like mypy and pyright, assume a subclass does not add `__bool__` or `__len__`. + assert_type(x and x.name, str | None) "#, );