Home > Net >  Python dataclass inferred fields
Python dataclass inferred fields

Time:07-09

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

CodePudding user response:

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}" 

CodePudding user response:

Just use a Python property in your class definition:



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
 @property
 def cacheKey(self):
     return f"{self.uuid}:{self.date}:{self.requestType}" # Expressing the idea

This is the most straightforward approach. The only drawback is that cacheKey won't show up as a field of your class if you use serialization methods such as daclasses.asdict.

  • Related