Skip to content

Commit

Permalink
Resolve the currency by symbol on Currency.__init__
Browse files Browse the repository at this point in the history
When instantiating the Currency class we need to resolve a `str`
currency symbol to its definition class to preserve any attribute
overrides.

Resolves kalaspuff#254
  • Loading branch information
Whiskey River committed Mar 21, 2024
1 parent 1e89e0d commit ede88e6
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 0 deletions.
4 changes: 4 additions & 0 deletions stockholm/currency.py
Original file line number Diff line number Diff line change
Expand Up @@ -321,6 +321,10 @@ def __new__(
) -> BaseCurrency:
if not cls._meta:
raise TypeError("'BaseCurrency' object is not callable")

if currency and isinstance(currency, str):
currency = getattr(cls, currency, currency)

return cast(
BaseCurrency,
BaseCurrencyType(
Expand Down
35 changes: 35 additions & 0 deletions tests/test_currency.py
Original file line number Diff line number Diff line change
Expand Up @@ -185,6 +185,41 @@ class EUR(BaseCurrency):
assert str(m) == "100 CarlosCoin"


def test_custom_currency_attributes():
class _XYZ(BaseCurrency):
ticker = "XYZ"
decimal_digits = 5
interchangeable_with = ("CNH", "RMB")
preferred_ticker = "ZYX"

class Currency(BaseCurrency):
XYZ = _XYZ

c1 = Currency("XYZ")
assert c1 != Money(0, Currency.XYZ)
assert c1.decimal_digits == _XYZ.decimal_digits
assert c1.interchangeable_with == _XYZ.interchangeable_with
assert c1.preferred_ticker == _XYZ.preferred_ticker

c2 = Currency(c1)
assert c2.ticker == "XYZ"
assert c2 == c1
assert str(c2) == "XYZ"
assert c2 == "XYZ"

c3 = Currency()
assert c3.ticker == ""
assert c3 != c1
assert c3 == ""
assert str(c3) == ""
assert c3 != Money(0, Currency.XYZ)

c4 = Currency(Currency.XYZ)
assert c4.ticker == "XYZ"
assert c4 == c1
assert c4 == "XYZ"


def test_currency_hashable() -> None:
class CNY(BaseCurrency):
interchangeable_with = ("CNH", "RMB")
Expand Down

0 comments on commit ede88e6

Please sign in to comment.