Search code examples
python-3.xpython-dataclasses

dictionary get method for list of dataclass objects - find dataclass with specific variable value in list of dataclasses


###It seems to me there has to be nicer way find a dataclass object than to loop through all to find the specific one.

#My way, that I hope to improve:
def changeValueOf(primaryKey):
    for item in self.addlist:
        if item.id == primaryKey:
            # Do stuff...


#Basics:
listOfKeys = "AA BB CC".split()

@dataclass
class Feld:
    id: str
    value1: str
    value2: str
    value3: str

self.addlist: List = []

for element in Daten:
    data = Feld(element[0], element[1], element[2], int(element[3]))
    self.addlist.append(data)

Solution

  • A common and efficient approach to keeping track of all instances of a class is to store each instance in a class variable of a dict by a certain key, and use a class method to retrieve an instance by the key. In your case, use the id attribute as the key:

    from typing import ClassVar
    from dataclasses import dataclass
    
    @dataclass
    class Feld:
        _id_to_instance: ClassVar[dict] = {}
        id: str
        value: str
    
        def __post_init__(self):
            self._id_to_instance[self.id] = self
    
        @classmethod
        def get_instance_by_id(cls, id):
            return cls._id_to_instance[id]
    

    so that:

    for id, value in ('id1', 'value1'), ('id2', 'value2'):
        Feld(id, value)
    
    print(Feld.get_instance_by_id('id2'))
    

    outputs:

    Feld(id='id2', value='value2')
    

    Demo: https://ideone.com/KgQH5y