[Python] How can I make all attributes in a Python dataclass optional without rewriting each...

Discussão em 'Python' iniciado por Stack, Setembro 1, 2025.

  1. Stack

    Stack Membro Participativo

    I have this data class:

    @dataclass
    class User:
    id: str
    name: str
    pwd: str
    picture: str
    url: str
    age: int
    # many, many more attributes


    Now, I have to make all of the attributes of my data class optional because of a change in the data I am receiving.

    I know I can do something like this:

    @dataclass
    class User:
    id: Optional[str] = None
    name: Optional[str] = None
    # and so on for the 25-30 attributes I have


    But is there a more efficient way to accomplish this without having to manually write Optional[..] = None for every line?

    For example, I used to get data like:

    attributes = {"id": "18ut2", "pwd": "qwerty", "name": "John Doe", "picture": None, "age": None, "url": "www.example.com"}
    user = User(**attributes)


    Before, if the attribute was None, the key was not omitted. Unlike now, when a key is None, the entire key is omitted.

    Example of current data:

    attributes = {"id": "18ut2", "pwd": "qwerty", "name": "John Doe", "url": "www.example.com"} # No picture or age key anymore
    user = User(**attributes) # Now throws an error


    Error:

    TypeError: User.__init__() missing 2 required positional arguments: 'picture' and 'age'


    Note: I know overriding __init__ or using __init_subclass__, but those come with limitations, so I am looking for a solution that avoids that.

    Continue reading...

Compartilhe esta Página