Implementing type-safe money in Python using phantom types is an advanced technique that leverages Python's type system to ensure correctness at compile time (or during static type checking with tools like mypy). Phantom types are a concept from functional programming where types are used to enforce constraints without carrying runtime data. In the context of money, phantom types can help ensure that operations on monetary values are type-safe, such as preventing accidental mixing of different currencies.
Below, I'll walk you through how to implement type-safe money in Python using phantom types, with explanations and examples.
Key Goals
- Type Safety: Ensure that operations on money (e.g., addition, subtraction) are only allowed between monetary values of the same currency.
- Phantom Types: Use types to encode currency information without storing it as runtime data.
- Static Type Checking: Use
mypy or similar tools to enforce type safety at "compile time."
- Ergonomics: Provide a clean and intuitive API for working with money.
Step 1: Setup and Dependencies
To implement this, you'll need:
- Python 3.7+ (for type annotations and
dataclasses).
mypy for static type checking (install via pip install mypy).
We'll use the typing module to create generic types and phantom types, and dataclasses to reduce boilerplate code.
Step 2: Define the Phantom Type for Currency
Phantom types are types that exist only at the type level and do not carry runtime data. In this case, we'll use phantom types to represent different currencies (e.g., USD, EUR). We'll use Python's typing.Generic to create a generic Money class parameterized by a currency type.
First, let's define marker types for currencies. These are empty classes that exist solely to distinguish currencies at the type level.
from typing import Generic, TypeVar
from dataclasses import dataclass
# Currency marker types (phantom types)
class USD: pass
class EUR: pass
class JPY: pass
# Type variable for currency
Currency = TypeVar("Currency")
Here, USD, EUR, and JPY are phantom types. They don't carry any runtime data but will be used to parameterize the Money class.
Step 3: Define the Money Class
The Money class will be generic over the Currency type variable. It will store the amount (as a decimal.Decimal for precision) but not the currency, as the currency is encoded in the type system.
from decimal import Decimal
@dataclass(frozen=True)
class Money(Generic[Currency]):
amount: Decimal
def __add__(self, other: "Money[Currency]") -> "Money[Currency]":
if not isinstance(other, Money):
raise TypeError(f"Cannot add {type(other)} to Money")
return Money[Currency](self.amount + other.amount)
def __sub__(self, other: "Money[Currency]") -> "Money[Currency]":
if not isinstance(other, Money):
raise TypeError(f"Cannot subtract {type(other)} from Money")
return Money[Currency](self.amount - other.amount)
def __str__(self) -> str:
return f"{self.amount}"
Key points:
- The
Money class is generic over Currency, meaning it can be instantiated as Money[USD], Money[EUR], etc.
- The
__add__ and __sub__ methods are type-safe: they only allow operations between Money instances of the same currency (enforced by the type checker).
- We use
Decimal for precise arithmetic, which is critical for financial calculations.
- The
frozen=True argument to @dataclass makes the class immutable, which is a good practice for money to prevent accidental modifications.
Step 4: Create Currency-Specific Constructors
To make the API ergonomic, we'll provide helper functions to create Money instances for specific currencies. These functions will also help enforce type safety by associating the correct phantom type with each currency.
def usd(amount: Decimal) -> Money[USD]:
return Money[USD](amount)
def eur(amount: Decimal) -> Money[EUR]:
return Money[EUR](amount)
def jpy(amount: Decimal) -> Money[JPY]:
return Money[JPY](amount)
These helper functions ensure that the type checker knows the currency of the Money instance being created.
Step 5: Example Usage
Now let's see how this works in practice. We'll write some code to demonstrate type-safe operations and how the type checker catches errors.
# Example usage
if __name__ == "__main__":
# Create money in different currencies
usd_10 = usd(Decimal("10.00"))
usd_20 = usd(Decimal("20.00"))
eur_15 = eur(Decimal("15.00"))
# Type-safe addition (same currency)
usd_sum = usd_10 + usd_20
print(f"USD sum: {usd_sum}") # Output: USD sum: 30.00
# Type-safe subtraction (same currency)
usd_diff = usd_20 - usd_10
print(f"USD diff: {usd_diff}") # Output: USD diff: 10.00
# Type error: Adding different currencies (caught by mypy)
try:
invalid_sum = usd_10 + eur_15 # mypy will flag this as an error
except TypeError as e:
print(f"TypeError: {e}")
If you run mypy on this code, it will catch the type error in the line usd_10 + eur_15 because Money[USD] and Money[EUR] are distinct types. The error message will look something like this:
error: Argument 1 to "__add__" of "Money" has incompatible type "Money[EUR]"; expected "Money[USD]"
Step 6: Adding Currency Conversion (Optional)
To make the system more practical, you might want to support currency conversion. This requires a way to convert between Money instances of different currencies, which involves changing the phantom type. Here's an example of how to implement currency conversion:
from typing import Type, cast
# Mock exchange rates (in practice, fetch from an API or database)
EXCHANGE_RATES = {
(USD, EUR): Decimal("0.85"),
(EUR, USD): Decimal("1.18"),
(USD, JPY): Decimal("110.00"),
(JPY, USD): Decimal("0.0091"),
}
def convert_currency(
money: Money[Currency], to_currency: Type[Currency]
) -> Money[Currency]:
if type(money) is not Money:
raise TypeError("Can only convert Money instances")
# If the currencies are the same, no conversion needed
if money.__orig_class__.__args__[0] is to_currency: # type: ignore
return money
# Look up the exchange rate
from_currency = money.__orig_class__.__args__[0] # type: ignore
rate = EXCHANGE_RATES.get((from_currency, to_currency))
if rate is None:
raise ValueError(f"No exchange rate available for {from_currency} to {to_currency}")
# Perform the conversion
converted_amount = money.amount * rate
return cast(Money[Currency], Money[to_currency](converted_amount))
# Example usage of currency conversion
if __name__ == "__main__":
usd_100 = usd(Decimal("100.00"))
eur_converted = convert_currency(usd_100, EUR)
print(f"Converted USD 100 to EUR: {eur_converted}") # Output: Converted USD 100 to EUR: 85.00
# Type-safe addition after conversion
eur_15 = eur(Decimal("15.00"))
eur_total = eur_converted + eur_15
print(f"EUR total: {eur_total}") # Output: EUR total: 100.00
Key points:
- The
convert_currency function uses cast to tell the type checker that the result is a Money instance of the target currency.
- We use runtime type introspection (
__orig_class__.__args__[0]) to determine the source currency, as this information is not stored in the instance but is encoded in the type.
- Exchange rates are mocked here, but in a real application, you'd fetch them from a reliable source.
Step 7: Running and Testing
To test the code, save it in a file (e.g., money.py) and run mypy to check for type errors:
mypy money.py
If there are no type errors, you can run the script directly:
python money.py
Step 8: Limitations and Considerations
- Runtime Type Safety: While this approach provides compile-time type safety, it doesn't prevent runtime errors entirely. For example, if you bypass the type system using
cast or other unsafe operations, you could still mix currencies at runtime. To mitigate this, you could add runtime checks (e.g., store the currency as a runtime attribute and validate it during operations).
- Performance: The use of phantom types has no runtime performance overhead, as the type information is erased at runtime. However, if you add runtime checks, there may be a small performance cost.
- Ergonomics: The API is ergonomic for simple use cases, but more complex operations (e.g., handling multiple currencies in a single transaction) may require additional utilities.
- Exchange Rates: In a real application, exchange rates should be fetched dynamically and include metadata like the date of the rate to ensure accuracy.
Step 9: Full Code
Here's the complete code for reference:
from typing import Generic, TypeVar, Type, cast
from decimal import Decimal
from dataclasses import dataclass
# Currency marker types (phantom types)
class USD: pass
class EUR: pass
class JPY: pass
# Type variable for currency
Currency = TypeVar("Currency")
@dataclass(frozen=True)
class Money(Generic[Currency]):
amount: Decimal
def __add__(self, other: "Money[Currency]") -> "Money[Currency]":
if not isinstance(other, Money):
raise TypeError(f"Cannot add {type(other)} to Money")
return Money[Currency](self.amount + other.amount)
def __sub__(self, other: "Money[Currency]") -> "Money[Currency]":
if not isinstance(other, Money):
raise TypeError(f"Cannot subtract {type(other)} from Money")
return Money[Currency](self.amount - other.amount)
def __str__(self) -> str:
return f"{self.amount}"
# Helper functions to create Money instances
def usd(amount: Decimal) -> Money[USD]:
return Money[USD](amount)
def eur(amount: Decimal) -> Money[EUR]:
return Money[EUR](amount)
def jpy(amount: Decimal) -> Money[JPY]:
return Money[JPY](amount)
# Mock exchange rates
EXCHANGE_RATES = {
(USD, EUR): Decimal("0.85"),
(EUR, USD): Decimal("1.18"),
(USD, JPY): Decimal("110.00"),
(JPY, USD): Decimal("0.0091"),
}
def convert_currency(
money: Money[Currency], to_currency: Type[Currency]
) -> Money[Currency]:
if type(money) is not Money:
raise TypeError("Can only convert Money instances")
if money.__orig_class__.__args__[0] is to_currency: # type: ignore
return money
from_currency = money.__orig_class__.__args__[0] # type: ignore
rate = EXCHANGE_RATES.get((from_currency, to_currency))
if rate is None:
raise ValueError(f"No exchange rate available for {from_currency} to {to_currency}")
converted_amount = money.amount * rate
return cast(Money[Currency], Money[to_currency](converted_amount))
# Example usage
if __name__ == "__main__":
# Create money in different currencies
usd_10 = usd(Decimal("10.00"))
usd_20 = usd(Decimal("20.00"))
eur_15 = eur(Decimal("15.00"))
# Type-safe addition (same currency)
usd_sum = usd_10 + usd_20
print(f"USD sum: {usd_sum}") # Output: USD sum: 30.00
# Type-safe subtraction (same currency)
usd_diff = usd_20 - usd_10
print(f"USD diff: {usd_diff}") # Output: USD diff: 10.00
# Currency conversion
usd_100 = usd(Decimal("100.00"))
eur_converted = convert_currency(usd_100, EUR)
print(f"Converted USD 100 to EUR: {eur_converted}") # Output: Converted USD 100 to EUR: 85.00
# Type-safe addition after conversion
eur_total = eur_converted + eur_15
print(f"EUR total: {eur_total}") # Output: EUR total: 100.00
Conclusion
Using phantom types in Python, we can create a type-safe representation of money that prevents errors like mixing currencies during operations. This approach leverages Python's type system and static type checkers like mypy to catch errors early, making the code more robust and maintainable. While this example focuses on money, the same technique can be applied to other domains where type safety is critical, such as units of measure (e.g., length, weight).