Created
February 17, 2023 22:09
-
-
Save jcrist/f476bb64e55b2af4f6911f46f12bf4b4 to your computer and use it in GitHub Desktop.
An example of using `msgspec`, mirroring the examples at https://github.com/ArjanCodes/2023-attrs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from datetime import date | |
from enum import StrEnum, auto | |
from typing import Annotated | |
from msgspec import Struct, Meta | |
class OrderStatus(StrEnum): | |
OPEN = auto() | |
CLOSED = auto() | |
class Product(Struct): | |
name: str | |
category: str | |
shipping_weight: Annotated[float, Meta(ge=0)] | |
unit_price: Annotated[int, Meta(ge=0)] | |
tax_percent: Annotated[float, Meta(ge=0, le=0)] | |
class Order(Struct): | |
status: OrderStatus | |
creation_date: date = date.today() | |
products: list[Product] = [] | |
def add_product(self, product: Product) -> None: | |
self.products.append(product) | |
@property | |
def sub_total(self) -> int: | |
return sum((product.unit_price for product in self.products)) | |
@property | |
def tax(self) -> float: | |
return sum( | |
(product.unit_price * product.tax_percent for product in self.products) | |
) | |
@property | |
def total_price(self) -> float: | |
return self.sub_total + self.tax | |
@property | |
def total_shipping_weight(self) -> float: | |
return sum((product.shipping_weight for product in self.products)) | |
def main() -> None: | |
banana = Product( | |
name="banana", | |
category="fruit", | |
shipping_weight=0.5, | |
unit_price=215, | |
tax_percent=0.07, | |
) | |
mango = Product( | |
name="mango", | |
category="fruit", | |
shipping_weight=2, | |
unit_price=319, | |
tax_percent=0.11, | |
) | |
expensive_mango = Product( | |
name="Mango", | |
category="Fruit", | |
shipping_weight=4.0, | |
unit_price=800, | |
tax_percent=0.20, | |
) | |
order = Order(status=OrderStatus.OPEN) | |
for product in [banana, mango, expensive_mango]: | |
order.add_product(product) | |
print(f"Comparison between mango and expensive mango: {mango == expensive_mango}") | |
print(f"Total order price: ${order.total_price/100:.2f}") | |
print(f"Subtotal order price: ${order.sub_total/100:.2f}") | |
print(f"Value paid in taxes: ${order.tax/100:.2f}") | |
print(f"Total weight order: {order.total_shipping_weight} kg") | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment