Skip to content

Commit

Permalink
Use __class_getitem__ for more specific non-subscript errors (#13596)
Browse files Browse the repository at this point in the history
  • Loading branch information
charliermarsh authored Oct 1, 2024
1 parent 0a6dc8e commit 961fc98
Showing 1 changed file with 34 additions and 3 deletions.
37 changes: 34 additions & 3 deletions crates/red_knot_python_semantic/src/types/infer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1327,12 +1327,13 @@ impl<'db> TypeInferenceBuilder<'db> {
&mut self,
node: AnyNodeRef,
non_subscriptable_ty: Type<'db>,
method: &str,
) {
self.add_diagnostic(
node,
"non-subscriptable",
format_args!(
"Cannot subscript object of type '{}' with no `__getitem__` method.",
"Cannot subscript object of type '{}' with no `{method}` method.",
non_subscriptable_ty.display(self.db)
),
);
Expand Down Expand Up @@ -2627,10 +2628,16 @@ impl<'db> TypeInferenceBuilder<'db> {
.call(self.db, &[slice_ty])
.unwrap_with_diagnostic(self.db, value.as_ref().into(), self);
}

self.non_subscriptable_diagnostic(
(&**value).into(),
value_ty,
"__class_getitem__",
);
} else {
self.non_subscriptable_diagnostic((&**value).into(), value_ty, "__getitem__");
}

// Otherwise, emit a diagnostic.
self.non_subscriptable_diagnostic((&**value).into(), value_ty);
Type::Unknown
}
}
Expand Down Expand Up @@ -6791,6 +6798,30 @@ mod tests {
Ok(())
}

#[test]
fn subscript_class_getitem_unbound() -> anyhow::Result<()> {
let mut db = setup_db();

db.write_dedented(
"/src/a.py",
"
class NotSubscriptable:
pass
a = NotSubscriptable[0]
",
)?;

assert_public_ty(&db, "/src/a.py", "a", "Unknown");
assert_file_diagnostics(
&db,
"/src/a.py",
&["Cannot subscript object of type 'Literal[NotSubscriptable]' with no `__class_getitem__` method."],
);

Ok(())
}

#[test]
fn subscript_not_callable_getitem() -> anyhow::Result<()> {
let mut db = setup_db();
Expand Down

0 comments on commit 961fc98

Please sign in to comment.