Issue with creation of nested data classes

Question:

I’m trying to create nested data classes:

from dataclasses import dataclass, field
import datetime
from typing import List


@dataclass
class LineItem:
    displayName: str
    compareAtPrice: float
    discountedPrice: float
    pricing: str = field(init=False)

    def __post_init__(self):
        self.pricing = (
            "regular" if self.compareAtPrice == self.discountedPrice else "on sale"
        )


@dataclass
class Order:
    createdAt: datetime
    lineItems: List[LineItem]

    def __post_init__(self):
        for l in self.lineItems:
            LineItem(**l)


data = {
    "createdAt": datetime.datetime.now(),
    "lineItems": [
        {
            "displayName": "lineitem 1",
            "compareAtPrice": 28.1,
            "discountedPrice": 28.1,
        },
        {
            "displayName": "lineitem 2",
            "compareAtPrice": 88.1,
            "discountedPrice": 78.1,
        },
    ],
}

print(Order(**data))

The output is missing the pricing field which should be populated by __post_init__ in class LineItem :

Order(createdAt=datetime.datetime(2023, 3, 9, 17, 18, 40, 136535), lineItems=[{'displayName': 'lineitem 1', 'compareAtPrice': 28.1, 'discountedPrice': 28.1}, {'displayName': 'lineitem 2', 'compareAtPrice': 88.1, 'discountedPrice': 78.1}])

What am I doing wrong here?

Asked By: Zin Yosrim

||

Answers:

You can do a small change like this in your Order class,

@dataclass
class Order:
    createdAt: datetime
    lineItems: List[LineItem]

    def __post_init__(self):
        self.lineItems = [LineItem(**l) for l in self.lineItems]
Answered By: Always Sunny
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.