Home > database >  Python: Using Dataclass field value as input when assigning value to another field in same class
Python: Using Dataclass field value as input when assigning value to another field in same class

Time:10-04

from dataclasses import dataclass
from utils import get_debt, get_profits

@dataclass
class Company:
    name: str
    debt: int
    profits: int

companies = [
    Company(
        name="XYZ",
        debt=1020423,
        profits=94324314,
    ),
    Company(
        name="KRT",
        debt=get_debt("KRT"),
        profits=get_profits("KRT"),
    ),
    Company(
        name="TRH",
        debt=get_debt("TRH"),
        profits=get_profits("TRH"),
    )
]

I have a dataclass where I mostly get the value of the fields debt and profit using a function that takes name as input. Is there a smart way to avoid typing the name thrice? get_debt(Position.name) does not work.

CodePudding user response:

You can use __post_init__ like so:

@dataclass
class Company:
    name: str
    debt: float | None = None
    profits: float | None = None

    def __post_init__(self):
        if self.debt is None:
            self.debt = get_debt(self.name)
        if self.profits is None:
            self.profits = get_profits(self.name)

Then simply not fill debt and profits:

Company(name="KRT")

Do I suggest doing it? Don't know. I usually prefer an anemic model, as get_profits and get_debt might change, thus composition has its advantages, but that's more of an architectural debate.

  • Related