Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Python

Records and aggregates

Model one record with named fields and calculate an aggregate across many records.

Version: Python 3.14; repository image, production runtime not attested

Syntax

@dataclass(frozen=True)

Model one record with named fields and calculate an aggregate across many records.

A dataclass can generate initialization and equality but its annotations do not validate incoming values. Enforce the example’s positive-quantity rule in post-initialization before summing line totals.

An empty collection contributes zero to the sum.

Examples

from dataclasses import dataclass
@dataclass(frozen=True)
class Line:
    cents: int
    qty: int
    def __post_init__(self):
        if type(self.qty) is not int or self.qty < 1:
            raise ValueError("positive integer quantity")
    def total(self):
        return self.cents * self.qty
def total(lines):
    return sum(line.total() for line in lines)
print(total([Line(125, 2), Line(40, 3)]), total([]))
try:
    Line(10, 0)
except ValueError as error:
    print(str(error))

Result

370 0
positive integer quantity

An empty collection contributes zero to the sum.

Sources