Implementing type-safe money in Python using phantom types is a powerful way to ensure correctness at compile time (or runtime in Python's case, since it's dynamically typed) by leveraging type hints and custom classes. Phantom types are types that are parameterized but don't use the parameter directly in their implementation, allowing you to encode additional type-level information.
In Python, we can simulate phantom types using type hints, generics, and runtime checks. Below is a step-by-step guide to implementing type-safe money in Python, ensuring that operations on different currencies (e.g., USD, EUR) are type-safe and prevent accidental mixing of currencies.
Step 1: Define the Core Concepts
- Phantom Type for Currency: We'll use a generic type to represent the currency as a phantom type. This ensures that operations are only allowed between money of the same currency.
- Money Class: A class to represent money, parameterized by the currency type.
- Runtime Checks: Since Python is dynamically typed, we'll add runtime checks to enforce type safety.
Step 2: Implementation
Here's a complete implementation using Python's typing module and runtime checks:
from typing import TypeVar, Generic, Union, overload
from decimal import Decimal
import abc
# Define a type variable for the currency (phantom type)
Currency = TypeVar("Currency")
# Define currency types (these are just marker classes to represent currencies)
class USD: pass
class EUR: pass
class JPY: pass
class Money(Generic[Currency]):
def __init__(self, amount: Union[int, float, Decimal], currency: type[Currency]):
self._amount = Decimal(str(amount)) # Use Decimal for precise arithmetic
self._currency = currency
@property
def amount(self) -> Decimal:
return self._amount
@property
def currency(self) -> type[Currency]:
return self._currency
def __repr__(self) -> str:
return f"{self._amount} {self._currency.__name__}"
# Type-safe addition
def __add__(self, other: "Money[Currency]") -> "Money[Currency]":
if not isinstance(other, Money):
raise TypeError(f"Cannot add {type(other)} to Money")
if self._currency != other._currency:
raise ValueError(f"Cannot add {self._currency.__name__} to {other._currency.__name__}")
return Money(self._amount + other._amount, self._currency)
# Type-safe subtraction
def __sub__(self, other: "Money[Currency]") -> "Money[Currency]":
if not isinstance(other, Money):
raise TypeError(f"Cannot subtract {type(other)} from Money")
if self._currency != other._currency:
raise ValueError(f"Cannot subtract {other._currency.__name__} from {self._currency.__name__}")
return Money(self._amount - other._amount, self._currency)
# Type-safe multiplication (by a scalar)
@overload
def __mul__(self, other: Union[int, float, Decimal]) -> "Money[Currency]": ...
def __mul__(self, other: Union[int, float, Decimal]) -> "Money[Currency]":
if not isinstance(other, (int, float, Decimal)):
raise TypeError(f"Cannot multiply Money by {type(other)}")
return Money(self._amount * Decimal(str(other)), self._currency)
# Type-safe division (by a scalar)
@overload
def __truediv__(self, other: Union[int, float, Decimal]) -> "Money[Currency]": ...
def __truediv__(self, other: Union[int, float, Decimal]) -> "Money[Currency]":
if not isinstance(other, (int, float, Decimal)):
raise TypeError(f"Cannot divide Money by {type(other)}")
return Money(self._amount / Decimal(str(other)), self._currency)
# Example usage
if __name__ == "__main__":
# Create money in different currencies
usd_10 = Money[USD](10, USD)
usd_20 = Money[USD](20, USD)
eur_15 = Money[EUR](15, EUR)
# Type-safe addition (same currency)
print(usd_10 + usd_20) # 30 USD
# Type-safe multiplication by scalar
print(usd_10 * 2) # 20 USD
# Type-safe division by scalar
print(usd_20 / 2) # 10 USD
# This will raise a ValueError (currency mismatch)
try:
print(usd_10 + eur_15)
except ValueError as e:
print(f"Error: {e}")
# This will raise a TypeError (invalid operation)
try:
print(usd_10 * eur_15)
except TypeError as e:
print(f"Error: {e}")
Step 3: Explanation of the Implementation
-
Phantom Types:
- The
Currency type variable is used to parameterize the Money class, but it doesn't appear in the runtime implementation (hence "phantom"). Instead, it provides type-level information to ensure type safety.
USD, EUR, and JPY are marker classes that represent different currencies. They are used as type arguments to Money.
-
Type Safety:
- The
Money class is generic over Currency, so Money[USD] and Money[EUR] are treated as distinct types by type checkers like mypy.
- Operations like
__add__ and __sub__ check that both operands have the same currency at runtime, raising a ValueError if they don't.
-
Decimal for Precision:
- We use
Decimal instead of float to avoid floating-point precision issues, which is critical for financial calculations.
-
Overloading:
- The
@overload decorator is used to provide type hints for operations like multiplication and division, ensuring that type checkers understand the return type is still Money[Currency].
-
Runtime Checks:
- Since Python is dynamically typed, we add runtime checks in methods like
__add__, __sub__, __mul__, and __truediv__ to enforce type safety.
Step 4: Type Checking with mypy
To ensure type safety at "compile time," you can use a static type checker like mypy. Save the code in a file (e.g., money.py) and run:
mypy money.py
mypy will catch type errors, such as attempting to add Money[USD] to Money[EUR], without running the code.
Step 5: Extending the Implementation
You can extend this implementation to include additional features, such as:
-
Currency Conversion:
Add a method to convert between currencies using exchange rates, ensuring type safety in the conversion process.
class ExchangeRate(Generic[Currency]):
def __init__(self, from_currency: type[Currency], to_currency: type[Currency], rate: Decimal):
self._from_currency = from_currency
self._to_currency = to_currency
self._rate = rate
def convert(self, money: "Money[Currency]") -> "Money[Currency]":
if money.currency != self._from_currency:
raise ValueError(f"Cannot convert {money.currency.__name__} using this exchange rate")
return Money(money.amount * self._rate, self._to_currency)
# Example usage
rate = ExchangeRate[USD, EUR](USD, EUR, Decimal("0.85"))
usd_100 = Money[USD](100, USD)
eur_amount = rate.convert(usd_100)
print(eur_amount) # 85 EUR
-
Formatting:
Add methods to format money amounts according to currency conventions (e.g., "$10.00" for USD, "€15.00" for EUR).
-
Comparison:
Implement __eq__, __lt__, etc., with type safety for comparisons between money of the same currency.
Step 6: Benefits of This Approach
- Type Safety: Prevents accidental mixing of currencies at both type-checking time (with
mypy) and runtime.
- Precision: Uses
Decimal for accurate financial calculations.
- Extensibility: Easy to add new currencies or features like conversion.
- Readability: The code is self-documenting, with type hints making the intent clear.
Step 7: Limitations
- Dynamic Typing: Python's dynamic typing means that some type safety relies on runtime checks, unlike languages like Haskell or Rust, where phantom types can be fully enforced at compile time.
- Verbosity: The implementation can be verbose, especially for a large number of currencies or operations.
- Tooling: You need to use tools like
mypy to get the full benefit of type safety, as Python itself doesn't enforce type hints.
Conclusion
This implementation provides a robust, type-safe way to handle money in Python using phantom types. By combining static type checking with runtime checks, you can prevent common errors in financial calculations, such as mixing currencies or using imprecise arithmetic.