[Python] Python dictionary vs dataclass (and metaclasses) for dynamic attributes

Discussão em 'Python' iniciado por Stack, Fevereiro 28, 2025.

  1. Stack

    Stack Membro Participativo

    Less object oriented snippet (1):

    class Trickjump(TypedDict):
    id: int
    name: str
    difficulty: str
    ...


    Dataclass snippet (2):

    @dataclass
    class Trickjump():
    id: IdAttr
    name: NameAttr
    difficulty: DifficultyAttr
    ...



    My issue lies in the fact that I can't decide which approach would be better in my case. I need attributes that are dynamically creatable with a name and custom functionality, where the user gives me the attribute's name as a string and the value as a string. I want to then use the attribute's custom functionality with the given value to produce a result.

    In the first code snippet, which I find is less object oriented, I could get the custom functionality of an attribute and use it with the value in the following way:

    Attributes.get("attr_name").sort_key(value)

    While in the second code snippet I would have to dynamically create classes with type(...) to act as attributes and it would also directly hold the value, probably best by using metaclasses.

    I think the first way is way less work, but I feel like the second option is something more advanced but possibly also a bit over the top. Which way do you think is the best for my scenario? Or is there another solution?

    Continue reading...

Compartilhe esta Página