Skip to content

Commit

Permalink
[red-knot] Infer type of class constructor call expression (astral-sh…
Browse files Browse the repository at this point in the history
…#13171)

This tiny PR implements the following type inference: the type of
`Foo(...)` will be `Foo`.

---------

Co-authored-by: Carl Meyer <carl@astral.sh>
  • Loading branch information
dylwil3 and carljm authored Aug 30, 2024
1 parent 828871d commit 3ceedf7
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 2 deletions.
4 changes: 2 additions & 2 deletions crates/red_knot_python_semantic/src/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -328,8 +328,8 @@ impl<'db> Type<'db> {
match self {
Type::Function(function_type) => function_type.returns(db).or(Some(Type::Unknown)),

// TODO: handle class constructors
Type::Class(_class_ty) => Some(Type::Unknown),
// TODO annotated return type on `__new__` or metaclass `__call__`
Type::Class(class) => Some(Type::Instance(*class)),

// TODO: handle classes which implement the Callable protocol
Type::Instance(_instance_ty) => Some(Type::Unknown),
Expand Down
18 changes: 18 additions & 0 deletions crates/red_knot_python_semantic/src/types/infer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2834,6 +2834,24 @@ mod tests {
Ok(())
}

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

db.write_dedented(
"src/a.py",
"
class Foo: ...
x = Foo()
",
)?;

assert_public_ty(&db, "src/a.py", "x", "Foo");

Ok(())
}

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

0 comments on commit 3ceedf7

Please sign in to comment.