[Python] How can I automatically create a type annotation for a dataclass method based on the...

Discussão em 'Python' iniciado por Stack, Maio 15, 2025.

  1. Stack

    Stack Membro Participativo

    Consider the following example:

    from dataclasses import dataclass
    import dataclasses
    from typing import Self


    @dataclass
    class Dataclass:
    a: int
    b: str
    c: list[int]

    def update_attrs(self, **kwargs) -> Self:
    return self.__class__(**(dataclasses.asdict(self) | kwargs))


    I can then do something like this:

    x = Dataclass(0, "1", [2])

    x.update_attrs(b="hello")


    Dataclass(a=0, b='hello', c=[2])


    I would like to automatically annotate the update_attrs method, so that instead of taking **kwargs as it currently does, it takes exactly: a: int, b: str, c: list[int] without writing it all out manually (one can imagine that in our actual usecase there are a lot of attributes to type out).

    This way, I get the benefit of autocompletion in my editor when calling Dataclass.update_attrs.

    Is something like this possible?

    Continue reading...

Compartilhe esta Página