Changeset View
Changeset View
Standalone View
Standalone View
looper/money.py
| import functools | from decimal import Decimal | ||||
| from typing import Dict, Iterable, List, Mapping, Union, overload | from typing import Dict, Iterable, List, Mapping, Union, overload | ||||
| import functools | |||||
| import babel.numbers | import babel.numbers | ||||
| from django.conf import settings | from django.conf import settings | ||||
| class CurrencyMismatch(ValueError): | class CurrencyMismatch(ValueError): | ||||
| """Raised when mixing currencies in one mathematical expression.""" | """Raised when mixing currencies in one mathematical expression.""" | ||||
| ▲ Show 20 Lines • Show All 103 Lines • ▼ Show 20 Lines | class Money: | ||||
| def __add__(self, other: 'Money') -> 'Money': | def __add__(self, other: 'Money') -> 'Money': | ||||
| self._assert_same_currency(other) | self._assert_same_currency(other) | ||||
| return Money(self._currency, self._cents + other._cents) | return Money(self._currency, self._cents + other._cents) | ||||
| def __sub__(self, other: 'Money') -> 'Money': | def __sub__(self, other: 'Money') -> 'Money': | ||||
| self._assert_same_currency(other) | self._assert_same_currency(other) | ||||
| return Money(self._currency, self._cents - other._cents) | return Money(self._currency, self._cents - other._cents) | ||||
| def __mul__(self, other: int) -> 'Money': | def __mul__(self, other: Union[int, Decimal]) -> 'Money': | ||||
| if isinstance(other, Money): | if isinstance(other, Money): | ||||
| raise TypeError('cannot multiply monetary quantities') | raise TypeError('cannot multiply monetary quantities') | ||||
| if not isinstance(other, int): | if not isinstance(other, (int, Decimal)): | ||||
| raise TypeError(f'unsupported type {type(other)}') | raise TypeError(f'unsupported type {type(other)}') | ||||
| if isinstance(other, Decimal): | |||||
| cents = round(self._cents * other) | |||||
| return Money(self._currency, cents) | |||||
| return Money(self._currency, self._cents * other) | return Money(self._currency, self._cents * other) | ||||
| __radd__ = __add__ | __radd__ = __add__ | ||||
| __rmul__ = __mul__ | __rmul__ = __mul__ | ||||
| @overload | @overload | ||||
| def __truediv__(self, divisor: int) -> List['Money']: | def __truediv__(self, divisor: int) -> List['Money']: | ||||
| # TODO(anna): Remove this overload. Instead just create a function | # TODO(anna): Remove this overload. Instead just create a function | ||||
| ▲ Show 20 Lines • Show All 147 Lines • Show Last 20 Lines | |||||