[Python] How to create "dynamic" Python types from dataclasses' members?

Discussão em 'Python' iniciado por Stack, Abril 11, 2025.

  1. Stack

    Stack Membro Participativo

    How to do add support for custom smart type completion in Python?

    Let's say I have a dataclass:

    @dataclass
    class MyData:
    mine: str
    yours: str

    def col(self, value: str):
    return "The column name is: " + value


    I want the value argument in col to be only one of mine or yours, i.e. only be one of the dataclass members. And I want the editor to understand this and autocomplete it, so that if I do data.col('mi...') it would autocomplete to 'mine'.

    This works if I manually specify the type:

    def col(self, value: Literal['mine', 'yours']):
    ...


    But ideally one would not replicate all the field names in the Literal type definition. Also, I would like to generate more value types (e.g. adding the '_now' suffix: Literal['mine', 'yours', 'mine_now', 'yours_now']).

    In summary, I would like to start from a dataclass, add a bunch of column names (statically - only thing required is the data class definition) and use those column names in a Literal type hint, so that editors and static type checkers can understand it.

    Is it possible to do this?

    Continue reading...

Compartilhe esta Página