Skip to content

How to annotate a function that returns a modified dataclass type #8812

Answered by erictraut
jrheard-seesaw asked this question in Q&A
Discussion options

You must be logged in to vote

How about a mix-in class?

from dataclasses import dataclass
from typing import Any, Self

class MyMethodMixin:
    @classmethod
    def my_method(cls, some_dict: dict[str, Any]) -> Self:
        return cls(**some_dict)

@dataclass
class MyClass(MyMethodMixin):
    foo: int

Or you could use __init_subclass__ together with dataclass_transform:

from dataclasses import dataclass, field
from typing import Any, Self, dataclass_transform

@dataclass_transform(field_specifiers=(field,))
class MyMethodBase:
    @classmethod
    def my_method(cls, some_dict: dict[str, Any]) -> Self:
        return cls(**some_dict)

    def __init_subclass__(cls) -> None:
        dataclass(cls)

class MyClass(MyMeth…

Replies: 1 comment 2 replies

Comment options

You must be logged in to vote
2 replies
@erictraut
Comment options

Answer selected by jrheard-seesaw
@jrheard-seesaw
Comment options

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants