I am currently in a situation where I have a class (Item) and a subclass (ScoredItem) and a function which makes an Item to a ScoredItem. The code works fine, but it requires me to re-create an existing object. It could happen that the Item
gets another attribute with a default value which would break the code. For example, if Item
got an attribute total_interactions : int = 0
, then the item list inserted into score_items
would likely not have total_interactions=0
. But if score_items
is not adjusted, then it silently fails. Is there a way to prevent this? Something like scored_item = ScoredItem(score=0.123, **item)
? Or item.score = 0.123; scored_item = ScoredItem(item)
?
I thought about composition vs. inheritance, but there are good indicators it should be inheritance.
MVCE
import random
from typing import List
from pydantic import BaseModel
class Item(BaseModel):
item_id: str
title: str
class ScoredItem(Item):
score: float
def get_items() -> List[Item]:
# generate n random items
n = 10
return [Item(item_id=str(i), title="foobar") for i in range(n)]
def score_items(items: List[Item]) -> List[ScoredItem]:
scored_items = []
for item in items:
scored_item = ScoredItem(
# Everything an Item has
item_id=item.item_id, title=item.title,
# Plus the score
score=random.random()
)
return scored_items
items = get_items()
scored_items = score_items(items)