How to add currency conversion?
- User
How to add currency conversion?
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
How to add currency conversion?
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
To add currency conversion to your type-safe Money implementation, you'll need to:
EUR → USD, USD → JPY)..convert() method that safely converts between currencies while preserving type safety.Here’s how to do it:
Store exchange rates in a dictionary (or fetch them from an API).
from typing import Dict, Tuple, Type
# Exchange rates: (from_currency, to_currency) → rate
_EXCHANGE_RATES: Dict[Tuple[Type, Type], float] = {
(EUR, USD): 1.08, # 1 EUR = 1.08 USD
(USD, EUR): 0.93, # 1 USD = 0.93 EUR
(USD, JPY): 150.0, # 1 USD = 150 JPY
(JPY, USD): 0.0067,
}
MoneyExtend the Money class with a .convert() method.
from typing import TypeVar, Generic, Type, overload
T = TypeVar('T')
U = TypeVar('U')
class Money(Generic[T]):
def __init__(self, amount: float) -> None:
self.amount = amount
def __add__(self, other: 'Money[T]') -> 'Money[T]':
return Money[T](self.amount + other.amount)
def convert(self, to_currency: Type[U]) -> 'Money[U]':
if (type(self), to_currency) in _EXCHANGE_RATES:
rate = _EXCHANGE_RATES[(type(self), to_currency)]
return Money[U](self.amount * rate)
else:
raise ValueError(f"No exchange rate from {type(self)} to {to_currency}")
def __repr__(self) -> str:
return f"{self.amount} {type(self).__name__}"
usd = Money[USD](100)
eur = Money[EUR](50)
# Convert USD to EUR
converted_eur = usd.convert(EUR)
print(converted_eur) # 93.0 EUR
# Convert EUR to USD
converted_usd = eur.convert(USD)
print(converted_usd) # 54.0 USD
# Invalid conversion (raises ValueError)
try:
jpy = Money[JPY](1000)
jpy.convert(EUR) # No rate defined → ValueError
except ValueError as e:
print(e) # "No exchange rate from JPY to EUR"
mypyStatic type checkers ensure you can't mix currencies accidentally:
usd = Money[USD](100)
eur = Money[EUR](50)
# Type-safe addition (only same currency)
total_usd = usd + usd # OK
# total_mixed = usd + eur # mypy error: Unsupported operand types
# Type-safe conversion
converted_eur: Money[EUR] = usd.convert(EUR) # OK
# converted_invalid: Money[USD] = eur.convert(USD) # OK (but runtime-checked)
forex-python).Money objects instead of modifying).decimal.Decimal for Precisionfrom decimal import Decimal, getcontext
class Money(Generic[T]):
def __init__(self, amount: Decimal | float | int) -> None:
self.amount = Decimal(str(amount)).quantize(Decimal("0.01"))
def convert(self, to_currency: Type[U]) -> 'Money[U]':
rate = _EXCHANGE_RATES.get((type(self), to_currency))
if rate is None:
raise ValueError(f"No exchange rate from {type(self)} to {to_currency}")
return Money[U](self.amount * Decimal(str(rate)))
Here’s the full version with conversion:
from typing import TypeVar, Generic, Type, Dict, Tuple
from decimal import Decimal
# Phantom types for currencies
class USD: pass
class EUR: pass
class JPY: pass
# Exchange rates (from, to) → rate
_EXCHANGE_RATES: Dict[Tuple[Type, Type], Decimal] = {
(EUR, USD): Decimal("1.08"),
(USD, EUR): Decimal("0.93"),
(USD, JPY): Decimal("150.0"),
}
T = TypeVar('T')
U = TypeVar('U')
class Money(Generic[T]):
def __init__(self, amount: Decimal | float | int) -> None:
self.amount = Decimal(str(amount)).quantize(Decimal("0.01"))
def __add__(self, other: 'Money[T]') -> 'Money[T]':
return Money[T](self.amount + other.amount)
def convert(self, to_currency: Type[U]) -> 'Money[U]':
rate = _EXCHANGE_RATES.get((type(self), to_currency))
if rate is None:
raise ValueError(f"No exchange rate from {type(self)} to {to_currency}")
return Money[U](self.amount * rate)
def __repr__(self) -> str:
return f"{self.amount} {type(self).__name__}"
# Example
usd = Money[USD](100)
eur = usd.convert(EUR) # 93.00 EUR
print(eur)
mypy).Decimal avoids floating-point precision issues.Would you like to extend this further (e.g., with operator overloading for * and /, or a currency API integration)?