Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
138 lines
4.9 KiB
Python
138 lines
4.9 KiB
Python
"""Immutable money amounts."""
|
|
|
|
from __future__ import annotations
|
|
|
|
from dataclasses import dataclass
|
|
from decimal import Decimal
|
|
from typing import List, Sequence, Union
|
|
|
|
from .rounding import round_decimal
|
|
|
|
_MINOR_UNITS = {"JPY": 0, "KRW": 0, "KWD": 3, "BHD": 3}
|
|
|
|
Amount = Union[int, str, Decimal]
|
|
|
|
|
|
def minor_units(currency: str) -> int:
|
|
"""Number of decimal places of the smallest unit of ``currency``."""
|
|
return _MINOR_UNITS.get(currency.upper(), 2)
|
|
|
|
|
|
class CurrencyMismatch(ValueError):
|
|
"""Raised when amounts in different currencies are combined."""
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class Money:
|
|
amount: Decimal
|
|
currency: str = "EUR"
|
|
|
|
def __post_init__(self) -> None:
|
|
if isinstance(self.amount, float):
|
|
raise TypeError("use str, int or Decimal for amounts, not float")
|
|
object.__setattr__(self, "amount", Decimal(self.amount))
|
|
object.__setattr__(self, "currency", self.currency.upper())
|
|
|
|
@classmethod
|
|
def zero(cls, currency: str = "EUR") -> "Money":
|
|
return cls(Decimal(0), currency)
|
|
|
|
@classmethod
|
|
def from_minor(cls, units: int, currency: str = "EUR") -> "Money":
|
|
return cls(Decimal(units).scaleb(-minor_units(currency)), currency)
|
|
|
|
def to_minor(self) -> int:
|
|
"""The amount as an integer number of minor units (cents)."""
|
|
scaled = self.amount.scaleb(minor_units(self.currency))
|
|
if scaled != scaled.to_integral_value():
|
|
raise ValueError("amount %s has sub-unit precision" % self.amount)
|
|
return int(scaled)
|
|
|
|
def rounded(self, mode: str = "half_even") -> "Money":
|
|
places = minor_units(self.currency)
|
|
return Money(round_decimal(self.amount, places, mode), self.currency)
|
|
|
|
def is_zero(self) -> bool:
|
|
return self.amount == 0
|
|
|
|
def _same_currency(self, other: "Money") -> None:
|
|
if not isinstance(other, Money):
|
|
raise TypeError("expected Money, got %s" % type(other).__name__)
|
|
if other.currency != self.currency:
|
|
raise CurrencyMismatch("%s and %s cannot be combined" % (self.currency, other.currency))
|
|
|
|
def __add__(self, other: "Money") -> "Money":
|
|
self._same_currency(other)
|
|
return Money(self.amount + other.amount, self.currency)
|
|
|
|
def __sub__(self, other: "Money") -> "Money":
|
|
self._same_currency(other)
|
|
return Money(self.amount - other.amount, self.currency)
|
|
|
|
def __neg__(self) -> "Money":
|
|
return Money(-self.amount, self.currency)
|
|
|
|
def __abs__(self) -> "Money":
|
|
return Money(abs(self.amount), self.currency)
|
|
|
|
def __mul__(self, factor: Amount) -> "Money":
|
|
if isinstance(factor, float):
|
|
raise TypeError("use str, int or Decimal for factors, not float")
|
|
return Money(self.amount * Decimal(factor), self.currency).rounded()
|
|
|
|
__rmul__ = __mul__
|
|
|
|
def __truediv__(self, divisor: Amount) -> "Money":
|
|
if isinstance(divisor, float):
|
|
raise TypeError("use str, int or Decimal for divisors, not float")
|
|
return Money(self.amount / Decimal(divisor), self.currency).rounded()
|
|
|
|
def __lt__(self, other: "Money") -> bool:
|
|
self._same_currency(other)
|
|
return self.amount < other.amount
|
|
|
|
def __le__(self, other: "Money") -> bool:
|
|
self._same_currency(other)
|
|
return self.amount <= other.amount
|
|
|
|
def __gt__(self, other: "Money") -> bool:
|
|
self._same_currency(other)
|
|
return self.amount > other.amount
|
|
|
|
def __ge__(self, other: "Money") -> bool:
|
|
self._same_currency(other)
|
|
return self.amount >= other.amount
|
|
|
|
def allocate(self, ratios: Sequence[int]) -> List["Money"]:
|
|
"""Split into ``len(ratios)`` parts proportional to ``ratios``.
|
|
|
|
Every part is a whole number of minor units and the parts always add up
|
|
to the original amount. Leftover minor units go one each to the first
|
|
parts with a non-zero ratio; negative amounts are split like positive
|
|
ones with the sign applied afterwards.
|
|
"""
|
|
if not ratios or any(r < 0 for r in ratios):
|
|
raise ValueError("ratios must be non-empty and non-negative")
|
|
total = sum(ratios)
|
|
if total == 0:
|
|
raise ValueError("ratios must not all be zero")
|
|
minor = self.to_minor()
|
|
sign = -1 if minor < 0 else 1
|
|
magnitude = abs(minor)
|
|
shares = [magnitude * r // total for r in ratios]
|
|
remainder = magnitude - sum(shares)
|
|
recipients = [i for i, r in enumerate(ratios) if r > 0]
|
|
for i in recipients[:remainder]:
|
|
shares[i] += 1
|
|
return [Money.from_minor(sign * share, self.currency) for share in shares]
|
|
|
|
def split(self, parts: int) -> List["Money"]:
|
|
"""Split into ``parts`` nearly equal parts that add up exactly."""
|
|
if parts < 1:
|
|
raise ValueError("parts must be positive")
|
|
return self.allocate([1] * parts)
|
|
|
|
def __str__(self) -> str:
|
|
shown = self.rounded()
|
|
return "%s %s" % (format(shown.amount, "f"), self.currency)
|