How to properly sort in a lazy loading way in Python? [closed]

1 day ago 4
ARTICLE AD BOX

Is there a way to reuse some loop to sort the final result?

I used the sorted but its not lazy loading, i wanted to find a way to rewrite my code in a way where everything is done lazyly. Its is possible? What solutions do you recommend me to do?

from dataclasses import dataclass from datetime import date import csv @dataclass class Product(): Id: int Code: str Quantity: int Price: float Date: str Country: str def read_rows(filename): with open(filename, "r") as f: reader = csv.DictReader(f) for row in reader: #print(row) yield row def parse_rows(rows): for row in rows: try: yield Product( Id=int(row["Id"]), Code=row["Code"], Quantity=int(row["Quantity"]), Price=float(row["Price"]), Date=row["Date"], Country=row["Country"], ) except ValueError as e: print("Error parsing:", e) def is_country(product, country): return product.Country == country def compute_total(products): for product in products: total = product.Quantity * product.UnitPrice yield (product, total) rows = read_rows("sales.csv") products = parse_rows(rows) filtered = filter(lambda p: is_country(p, "France"), products) with_totals = compute_total(filtered) for i in filtered: print(i)
Read Entire Article