Search code examples
python-3.xpython-dataclasses

Python dataclass inferred fields


Is it possible in python to have fields in a dataclass which infer their value from other fields in the dataclass? In this case the cacheKey is just a combination of other fields and I don't want to mention it explicitly in the object instantiation.

@dataclass
class SampleInput:
 uuid: str
 date: str
 requestType: str
 cacheKey = f"{self.uuid}:{self.date}:{self.requestType}" # Expressing the idea

Solution

  • You can use post_init to use the other fields:

    @dataclass
    class SampleInput:
       uuid: str
       date: str
       requestType: str
    
       def __post_init__(self):
            self.cacheKey = f"{self.uuid}:{self.date}:{self.requestType}"