pythonpython-3.xpython-dataclasses

Python dataclass: create property dynamically


I have a dataclass, I'd like to dynamically create property device_group after evaluating another property device_name. I'm currently doing it with @property decorator and it works if I access it with instance.device_group .

@dataclass
class Device:
    device_name: str
    uplinks: list
    @property
    def device_group(self) -> str:
        # do something here with self.device_name
        return device_group 

But the class instance won't have this property unless you try to access it with instance.device_group

  "unknown_device": {
    "device_name": "unknown_device",
    "uplinks": [
      {

Can the instance generate the device_group dynamically right after it was created? Or I better to call device_group() somewhere else and then assign result to the device_group property explicitly?


Solution

  • You could use post init processing:

    from dataclasses import dataclass, field
    
    @dataclass
    class Device:
        device_name: str
        uplinks: list
        device_group: str = field(init=False)
    
        def __post_init__(self):
            self.device_group = self.device_name + "_group"