Implementing type-safe money in Python can significantly reduce errors related to currency mix-ups or incorrect monetary operations (like adding dollars to euros). The phantom-types library allows you to create types that wrap existing types but add additional logical constraints or meaning to them without altering their runtime behavior. This is perfect for distinguishing between different currencies or ensuring operations are done with the correct monetary units.
Here's a step-by-step guide on how to implement type-safe money using phantom-types in Python:
Step 1: Install phantom-types
First, ensure you have phantom-types installed in your environment. You can install it via pip:
pip install phantom-types
Step 2: Define Currencies
We'll start by defining different currencies as phantom types. Each currency will be a distinct type, preventing accidental mixing.
from phantom_types import Phantom
from phantom_types.primitive import validate
# Define a base for our currencies, in this case, integers representing cents.
# This avoids floating-point precision issues common with monetary calculations.
class Currency(Phantom[int]):
"""Base phantom type for currencies."""
@classmethod
def __validate__(cls, value):
# Ensure value is an integer (representing cents)
validate(int, value)
# Optionally, you could validate that value >= 0 for non-negative amounts
# validate(value >= 0, "Amount cannot be negative")
# Now, define specific currencies
class USD(Currency):
"""United States Dollar"""
__name__ = "USD"
class EUR(Currency):
"""Euro"""
__name__ = "EUR"
class JPY(Currency):
"""Japanese Yen"""
__name__ = "JPY"
In the code above, Currency serves as a base phantom type for any currency, ensuring the underlying value is an integer (cents). Then, USD, EUR, and JPY are specific currencies. The __name__ attribute is overridden for better representation.
Step 3: Implement Money Operations
Now, let's create a Money class that uses these currency types. This class will support basic arithmetic operations but ensure they are type-safe (i.e., you can't add USD to EUR directly).
from typing import TypeVar, Generic, Union
from functools import total_ordering
C = TypeVar('C', bound=Currency)
@total_ordering
class Money(Generic[C]):
"""Represents an amount of money in a specific currency."""
def __init__(self, amount: C):
self.amount = amount
@classmethod
def zero(cls, currency_class: type[C]) -> 'Money[C]':
"""Creates a zero amount for the given currency."""
return cls(currency_class(0))
def __repr__(self):
return f"{self.amount.__class__.__name__}({self.amount})"
def __eq__(self, other: object) -> bool:
if not isinstance(other, Money):
return NotImplemented
if type(self.amount) != type(other.amount):
raise TypeError(f"Cannot compare {type(self.amount).__name__} with {type(other.amount).__name__}")
return self.amount == other.amount
def __lt__(self, other: 'Money[C]') -> bool:
# Ensures comparison is only between the same currencies
if type(self.amount) != type(other.amount):
raise TypeError(f"Cannot compare {type(self.amount).__name__} with {type(other.amount).__name__}")
return self.amount < other.amount
def __add__(self, other: 'Money[C]') -> 'Money[C]':
if type(self.amount) != type(other.amount):
raise TypeError(f"Cannot add {type(self.amount).__name__} to {type(other.amount).__name__}")
return Money(self.amount.__class__(self.amount + other.amount))
def __sub__(self, other: 'Money[C]') -> 'Money[C]':
if type(self.amount) != type(other.amount):
raise TypeError(f"Cannot subtract {type(other.amount).__name__} from {type(self.amount).__name__}")
return Money(self.amount.__class__(self.amount - other.amount))
def __mul__(self, factor: int) -> 'Money[C]':
# Multiplying money by a scalar, useful for things like "3 times $5"
return Money(self.amount.__class__(self.amount * factor))
# Optionally, implement division if needed (__truediv__, __floordiv__)
# Example usage
if __name__ == "__main__":
five_usd = Money(USD(500)) # $5.00
ten_usd = Money(USD(1000)) # $10.00
# This works
fifteen_usd = five_usd + ten_usd
print(fifteen_usd) # Outputs: USD(1500)
five_eur = Money(EUR(500)) # €5.00
# This raises TypeError: Cannot add USD to EUR
try:
mixed = five_usd + five_eur
except TypeError as e:
print(e)
# Comparison between different currencies also raises TypeError
try:
print(five_usd == five_eur)
except TypeError as e:
print(e)
What We Achieved:
- Type Safety: Operations (addition, subtraction, comparison) between monies of different currencies are guarded by type checks, preventing logically incorrect operations at runtime.
- Precision: By representing money in cents (or the smallest indivisible unit of the currency), we avoid floating-point arithmetic issues.
- Readability and Expressiveness: The code clearly expresses intent (
Money(USD(100)) is unmistakably $1.00).
- Extensibility: Adding a new currency is as simple as defining a new class (
class GBP(Currency): ...).
Note: While phantom-types enhances type hints and validation, Python's dynamic nature means some checks are still performed at runtime (e.g., ensuring you don't add USD to EUR). Static type checkers (like mypy) will help catch type-related errors before runtime, but the actual safeguards against mixing currencies in operations are implemented explicitly in the Money class's methods.
This pattern is quite powerful for domain-driven design, where the type system itself documents and enforces business rules. Enjoy your type-safe financial calculations!