Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Issue with creation of nested data classes

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading