Is there a way to assign all fields from a base dataclass to another one such that MyPy understands which fields are present?
from dataclasses import dataclass
@dataclass
class TypeA:
name: str
age: int
@dataclass
class TypeB(TypeA):
more: bool
def upgrade(a: TypeA) -> TypeB:
return TypeB(
more=False,
**a, # this is syntax I'm uncertain of
)
I can use ** on a dataclasses.asdict
or the __dict__
field, but that erases the type checking. For example, MyPy doesn't complain about this:
return TypeB(
**a.__dict__
)
Despite more
being missing. It appears that MyPy loses type information on __dict__
(as well as dataclasses.asdict).
I don't want to list individual fields for copying for two reasons:
- It's redundant
- I may miss an optional field which would not be caught
- I may later add an optiona/default field which would not be detected