Functional Weave
Code in TypeScript

money.amount@1.0.0

impl/python.py

947 bytes · the Python implementation · view raw

import re


# Money is declared in function.fune: integer minor units, never a float.
from .money_amount_types import Money

CURRENCY = re.compile(r"^[A-Z]{3}$")


def money(minor: int, currency: str) -> Money:
    if isinstance(minor, bool) or not isinstance(minor, int):
        raise TypeError("money() takes integer minor units, received %r" % (minor,))
    if not isinstance(currency, str) or not CURRENCY.match(currency):
        raise ValueError('"%s" is not an uppercase ISO 4217 currency code' % (currency,))
    return Money(minor=minor, currency=currency)


def is_money(value: object) -> bool:
    return isinstance(value, Money)


def assert_same_currency(a: Money, b: Money) -> None:
    """Guard against the silent nonsense of adding GBP to EUR."""
    if a.currency != b.currency:
        raise ValueError("currency mismatch: %s and %s" % (a.currency, b.currency))


def zero(currency: str) -> Money:
    return money(0, currency)