Implementing type-safe money in Python using phantom types is an interesting challenge. Phantom types are a concept from statically typed languages like Haskell, where types carry additional information at compile time without affecting runtime behavior. While Python is dynamically typed and doesn't natively support phantom types, we can simulate them using classes and type annotations to enforce constraints at runtime.
Below, I will explain how to implement type-safe money in Python using phantom types. The goal is to ensure that operations on monetary values are only allowed when the currencies match, preventing accidental mixing of different currencies.
Step-by-Step Implementation
1. Define the Phantom Type Concept
In Python, we can use classes to represent phantom types. These classes won't hold any runtime data but will serve as markers for type annotations.
from typing import Generic, TypeVar, NewType
# Define a type variable for currencies
Currency = TypeVar("Currency")
# Example currencies as phantom types
class USD:
pass
class EUR:
pass
class JPY:
pass
Here, USD, EUR, and JPY are phantom types representing different currencies. They don't store any data but act as markers for type annotations.
2. Define the Money Class
The Money class will encapsulate the amount and its associated currency. We'll use generics to associate the currency with the amount.
from typing import Generic, TypeVar
class Money(Generic[Currency]):
def __init__(self, amount: float):
self.amount = amount
def __repr__(self):
return f"{self.amount} {self.currency_name()}"
@classmethod
def currency_name(cls) -> str:
# Extract the name of the currency from the generic type
return cls.__orig_bases__[0].__args__[0].__name__
This class uses Generic[Currency] to associate a specific currency with the Money instance. The currency_name method extracts the name of the currency for display purposes.
3. Create Type-Safe Money Instances
We can now create type-safe money instances by subclassing Money with specific currency types.
class USDollar(Money[USD]):
pass
class Euro(Money[EUR]):
pass
class Yen(Money[JPY]):
pass
These subclasses represent money in specific currencies. For example, USDollar represents money in US dollars, and Euro represents money in euros.
4. Define Operations with Type Safety
To ensure type safety, we define operations (e.g., addition, subtraction) that only work when the currencies match.
from typing import TypeVar
C = TypeVar("C", bound=Currency)
def add_money(m1: Money[C], m2: Money[C]) -> Money[C]:
if not isinstance(m1, type(m2)):
raise TypeError("Cannot add money of different currencies")
return type(m1)(m1.amount + m2.amount)
def subtract_money(m1: Money[C], m2: Money[C]) -> Money[C]:
if not isinstance(m1, type(m2)):
raise TypeError("Cannot subtract money of different currencies")
return type(m1)(m1.amount - m2.amount)
These functions enforce type safety by checking that both operands are of the same currency type. If the currencies differ, a TypeError is raised.
5. Example Usage
Here's how you can use the type-safe money system:
# Create money instances
usd1 = USDollar(100.0)
usd2 = USDollar(50.0)
eur1 = Euro(75.0)
# Add money of the same currency
total_usd = add_money(usd1, usd2)
print(total_usd) # Output: 150.0 USD
# Subtract money of the same currency
remaining_usd = subtract_money(usd1, usd2)
print(remaining_usd) # Output: 50.0 USD
# Attempt to add money of different currencies
try:
invalid_total = add_money(usd1, eur1)
except TypeError as e:
print(e) # Output: Cannot add money of different currencies
Key Points
- Phantom Types: The
USD, EUR, and JPY classes act as phantom types, providing type annotations without runtime overhead.
- Generics: The
Money class uses generics to associate a specific currency with the amount.
- Type Safety: Operations like addition and subtraction enforce type safety by checking that both operands are of the same currency type.
- Runtime Enforcement: While Python's type system is dynamic, we use runtime checks to enforce type safety.
Limitations
- Python's type system is dynamic, so type annotations alone cannot prevent incorrect usage at runtime. Runtime checks (e.g.,
isinstance) are necessary to enforce constraints.
- This approach relies on disciplined usage of the
Money class and its subclasses.
If you need stricter compile-time guarantees, consider using a statically typed language like Haskell or Rust, which natively supports phantom types.
Let me know if you have further questions!