Python make optional all fields of @dataclass decorated object

Solution 1:

Yes there is a way to do this. However it will mess with your IDE's ability to do autocompletion and wont enforce any constraints that a dataclass is meant to have. So basically overriding alot of dataclass' safety features.

This code will first mark everything as None but will still allow you to pass in kwargs to the init to set as the value.

from dataclasses import dataclass


@dataclass
class Sample:
    field_one: int
    field_two: int

    def __init__(self, **kwargs):
        for k in self.__dataclass_fields__:
            setattr(self, k, None)

        for k, v in kwargs.items():
            setattr(self, k, v)

Sample() # Works, everything is None

Sample(field_one=10) # Works, everything is None except for field_one which is now equal to 10

Dry method for this so you don't have to copy and paste everywhere... Please look at the dataclass decorator and passing init=False

class AllPropertiesAsNone:
    def __init__(self, **kwargs):
        for k in self.__dataclass_fields__:
            setattr(self, k, None)

        for k, v in kwargs.items():
            setattr(self, k, v)


@dataclass(init=False)
class Sample(AllPropertiesAsNone):
    field_one: int
    field_two: int