How to annotate a function that returns a modified dataclass type #8812
-
Hi, I've encountered some code that looks like this: def dataclass_with_additional_method(cls):
result_cls = dataclass(cls) # apply the dataclass decorator
def from_dict(cls, some_dict):
return cls(**some_dict)
result_cls.from_dict = classmethod(from_dict)
return result_cls I'm glossing over some details here, but that's the overall shape of this function. It's used as a decorator for a number of classes, like this: @dataclass_with_additional_method
class MyClass:
foo: int I'm having a lot of trouble figuring out the right way to annotate this I think that the desired behavior would be for this function to take Just about every type signature I've tried causes one or more of these problems:
Is there anything I can do to the signature of |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
I'm thinking about nuking this decorator, updating all the callsites to use if TYPE_CHECKING:
from _typeshed import DataclassInstance
T = TypeVar("T", bound="DataclassInstance")
def from_dict(cls: type[T], data: dict[str, Any]) -> T:
return cls(**dict) (again, I'm handwaving over some details, mainly focusing on the overall types/shapes.) Does that seem like a better way forward? |
Beta Was this translation helpful? Give feedback.
How about a mix-in class?
Or you could use
__init_subclass__
together withdataclass_transform
: