Skip to content

Commit 5bab38e

Browse files
committed
[red-knot] Three-argument type-calls take 'str' as the first argument
1 parent 177afab commit 5bab38e

File tree

3 files changed

+29
-2
lines changed

3 files changed

+29
-2
lines changed

crates/red_knot_python_semantic/resources/mdtest/call/builtins.md

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,11 @@ reveal_type(type(1)) # revealed: Literal[int]
2626
But a three-argument call to type creates a dynamic instance of the `type` class:
2727

2828
```py
29+
class Base: ...
30+
2931
reveal_type(type("Foo", (), {})) # revealed: type
32+
33+
reveal_type(type("Foo", (Base,), {"attr": 1})) # revealed: type
3034
```
3135

3236
Other numbers of arguments are invalid
@@ -38,3 +42,21 @@ type("Foo", ())
3842
# error: [no-matching-overload] "No overload of class `type` matches arguments"
3943
type("Foo", (), {}, weird_other_arg=42)
4044
```
45+
46+
The following calls are also invalid, due to incorrect argument types:
47+
48+
```py
49+
class Base: ...
50+
51+
# error: [no-matching-overload] "No overload of class `type` matches arguments"
52+
type(b"Foo", (), {})
53+
54+
# TODO: this should be an error
55+
type("Foo", str, {})
56+
57+
# TODO: this should be an error
58+
type("Foo", (1, 2), {})
59+
60+
# TODO: this should be an error
61+
type("Foo", (Base,), {b"attr": 1})
62+
```

crates/red_knot_python_semantic/resources/mdtest/narrow/type.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,9 @@ No narrowing should occur if `type` is used to dynamically create a class:
7676

7777
```py
7878
def _(x: str | int):
79+
# The following diagnostic is valid, since the three-argument form of `type`
80+
# can only be called with `str` as the first argument.
81+
# error: [no-matching-overload] "No overload of class `type` matches arguments"
7982
if type(x, (), {}) is str:
8083
reveal_type(x) # revealed: str | int
8184
else:

crates/red_knot_python_semantic/src/types.rs

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2893,11 +2893,13 @@ impl<'db> Type<'db> {
28932893
),
28942894
Signature::new(
28952895
Parameters::new([
2896-
Parameter::positional_only(Some(Name::new_static("o")))
2897-
.with_annotated_type(Type::any()),
2896+
Parameter::positional_only(Some(Name::new_static("name")))
2897+
.with_annotated_type(KnownClass::Str.to_instance(db)),
28982898
Parameter::positional_only(Some(Name::new_static("bases")))
2899+
// TODO: Should be tuple[type, ...] once we have support for homogenous tuples
28992900
.with_annotated_type(Type::any()),
29002901
Parameter::positional_only(Some(Name::new_static("dict")))
2902+
// TODO: Should be `dict[str, Any]` once we have support for generics
29012903
.with_annotated_type(Type::any()),
29022904
]),
29032905
Some(KnownClass::Type.to_instance(db)),

0 commit comments

Comments
 (0)