4 ms·
Agreed. Also, Mypy's dict inference is too broad, making TypedDict a little less useful. For example, the following code raises a Mypy error even though `foo` c
by goodoldneon 4y ago
Agreed. Also, Mypy's dict inference is too broad, making TypedDict a little less useful. For example, the following code raises a Mypy error even though `foo` conforms to `Foo`:
import typing
class Foo(typing.TypedDict):
a: int
def do_thing(value: Foo) -> None:
return
foo = {"a": 1}
# error: Argument 1 to "do_thing" has incompatible type "Dict[str, int]"; expected "Foo"
do_thing(foo)
But TypeScript can figure it out:
interface Foo {
a: number
}
function doThing(value: Foo): void {
return
}
const foo = { a: 1 }
doThing(foo)
- bayesian_horse 4y agoThis is a misunderstanding of the Python type system. In the Typescript example you are depending on "foo" being structurally compatible to the "Foo" interface. In the Python case, "foo" and "Foo" might look structurally compatible, but they aren't. "Foo" isn't just a type, it's an object of type "class". You can for example print(Foo), you can't console.log(Foo). "foo" is not an instance of the Foo class. What you are looking for is "dict[str, object]".
- goodoldneon 4y agoTypedDicts fall under structural typing, not nominal typing. So Mypy is cool with this: import typing class Foo(typing.TypedDict): a: int def do_thing(value: Foo) -> None: return foo: Foo = {"a": 1} do_thing(foo) My complaint here is that Mypy doesn't go far enough with structural inference. I assume this is because it doesn't support anonymous TypedDicts, whereas TypeScript supports anonymous interfaces/types