Skip to content

Instantly share code, notes, and snippets.

@eterps
Created March 19, 2024 17:22
Show Gist options
  • Save eterps/b22c542540efb2c2b3692026cfee0c4f to your computer and use it in GitHub Desktop.
Save eterps/b22c542540efb2c2b3692026cfee0c4f to your computer and use it in GitHub Desktop.
from dataclasses import dataclass
@dataclass
class UnitQuantity:
value: int
@dataclass
class KilogramQuantity:
value: float
OrderQuantity = UnitQuantity | KilogramQuantity
an_order_qty_in_units = UnitQuantity(10)
an_order_qty_in_kg = KilogramQuantity(2.5)
def quantity_label(oq: OrderQuantity) -> str:
match (oq):
case UnitQuantity(n):
return f"{n} units"
case KilogramQuantity(n):
return f"{n} kg"
label = quantity_label(an_order_qty_in_kg)
print(label)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment