I have a dataclass with this structure:
from dataclasses import dataclass
from typing import List
@dataclass
class PartData:
id: int = 0
name: str = None
value: int = 0
@dataclass
class StockData:
stock_1: List[PartData] = None
stock_2: List[PartData] = None
def __getitem__(self, key):
return super().__getattribute__(key)
Now I create the dataclasses and fill them with items:
PARTS = [{"id": 1, "name": "screw"}, {"id": 3, "name": "bolt"}, {"id": 42, "name": "glue"}, {"id": 11, "name": "nail"}, {"id": 31, "name": "hammer"}, {"id": 142, "name": "paper"}]
dc_stock = StockData()
for p in PARTS:
dc_part = PartData()
dc_part.id = p["id"]
if dc_part.id % 2 == 0:
dc_stock_list = "stock_1"
else:
dc_stock_list = "stock_2"
if getattr(dc_stock, dc_stock_list) == None:
setattr(dc_stock, dc_stock_list, [dc_part])
else:
dc_stock[dc_stock_list].append(dc_part)
print(dc_stock)
# StockData(stock_1=[PartData(id=42, name=None, value=0), PartData(id=142, name=None, value=0)],
# stock_2=[PartData(id=1, name=None, value=0), PartData(id=3, name=None, value=0), PartData(id=11, name=None, value=0), PartData(id=31, name=None, value=0)])
I know I can loop over all items and compare them, but can I define a method that takes part_id as an argument and can update any item in dc_stock with that part_id with a new value? Can this be implemented as a method of StockData? Suppose I do not know if the part is in stock_1 or stock_2.
Edit
For better understanding I want to share my approach, which looks very loopy and costy to me:
@dataclass
class StockData:
stock_1: List[PartData] = None
stock_2: List[PartData] = None
def __getitem__(self, key):
return super().__getattribute__(key)
def update_part(self, id, value):
for stock_list in [f for f in fields(self) if f.name.startswith("stock")]:
stock = getattr(self, stock_list.name)
if len(stock) > 0:
for part in stock:
if part.id == id:
part.value = value
return None
print(dc_stock)
dc_stock.update_part(1, 10)
print(dc_stock)