I have a dataclass let's say:
from dataclasses import dataclass
@dataclass
class Foo:
bar: int
baz: int
I have a function that is called from an API receiving json and loading it as a Dict:
def handler(foo) -> Foo:
return Foo(**foo)
Is there a way to type foo without having to actually create a TypedDict
mirror of the dataclass?
Such as:
from typing_extensions import TypedDict
class SerializedFoo(TypedDict):
bar: int
baz: int
I find it weird to have to define both.
def make_typed_dict(name, cls): return TypedDict(name, {f.name: f.type for f in dataclasses.fields(cls)})
; SerializedFoo = make_typed_dict('SerializedFoo', Foo)`. – Kinematicsdataclasses
could providemake_typed_dict
as a class method instead of making you define it yourself. – Kinematicsfoo
has nothing whatsoever to do with the dataclassFoo
. The former is a generic container type, the latter is a specific concrete type. As chepner said, the fact that dict keys and attributes match has no bearing on this. And I agree with SUTerliakov that no type checker will interpret this any other way. – Halflightfoo
actually improve things? From a typing perspective, callinghandler
is equivalent to callingFoo
– why not use the latter directly? At some point you must tell the type checker that the input is fine and it is much simpler for that point to beFoo
than some boilerplate. – Swaziland