To implement type-safe money in Python using phantom types, we can leverage Python’s typing module, specifically Generic and TypeVar, to encode currency information in the type system rather than in the data itself. This approach mimics the behavior of phantom types found in statically-typed languages like Haskell or Scala.
🔧 Key Concepts
Phantom Types: These are types that are not used in the data but are used to enforce constraints at the type level. In Python, we can simulate this using generic type parameters.
Type Safety: Enforced via the type system (e.g., using mypy), not at runtime.
Runtime Behavior: Python is dynamically typed, so the type system does not enforce these constraints at runtime. We rely on static type checkers like mypy to enforce them.
🧱 Implementation Steps
1. Define a Base Currency Class
We start by defining a base Currency class. This class will serve as a marker to differentiate between different currencies.
python
class Currency:
pass
2. Define Specific Currency Subclasses
Next, define specific currency classes that inherit from Currency. These will act as phantom types.
python
class USD(Currency):
pass
class EUR(Currency):
pass
3. Define a Generic Money Class
Now, define a generic Money class that uses a TypeVar to represent the currency type. This is where the phantom type comes into play — the actual Money instance does not store the currency type, but it is used in the type signature.
python
from typing import Generic, TypeVar
T = TypeVar('T', bound=Currency)
class Money(Generic[T]):
def __init__(self, amount: float):
self.amount = amount
def add(self, other: 'Money[T]') -> 'Money[T]':
return Money(self.amount + other.amount)
4. Use the Money Class with Type Hints
Now, you can create Money instances with specific currency types, and the type checker will ensure you can only add money of the same currency.
python
usd1 = Money[USD](100.0)
usd2 = Money[USD](50.0)
total_usd = usd1.add(usd2) # ✅ Valid
eur1 = Money[EUR](200.0)
# total_eur = usd1.add(eur1) # ❌ mypy will flag this as an error
🧪 Runtime Behavior
At runtime, Python does not enforce these type constraints. You can still do:
python
usd1 = Money[USD](100.0)
eur1 = Money[EUR](200.0)
usd1.add(eur1) # ✅ This runs, but is type-unsafe
To enforce type safety at runtime, you would need to add explicit checks, which would deviate from the "phantom" approach. However, the main benefit of this technique is static type safety via tools like mypy.
🧪 Example with mypy
Install mypy if not already installed:
bash
pip install mypy
Then, run:
bash
mypy your_script.py
If you try to add USD and EUR, mypy will raise an error:
code
error: Argument 1 to "add" of "Money" has incompatible type "Money[EUR]"; expected "Money[USD]"
✅ Summary
Feature
Description
Phantom Type
The currency is encoded in the type system, not in the data.
Type Safety
Enforced at compile time via mypy.
Runtime Behavior
Python does not enforce type constraints at runtime.
Use Case
Ensures that operations like add are only performed on compatible money types.
📦 Final Code
python
from typing import Generic, TypeVar
class Currency:
pass
class USD(Currency):
pass
class EUR(Currency):
pass
T = TypeVar('T', bound=Currency)
class Money(Generic[T]):
def __init__(self, amount: float):
self.amount = amount
def add(self, other: 'Money[T]') -> 'Money[T]':
return Money(self.amount + other.amount)
# Example usage
usd1 = Money[USD](100.0)
usd2 = Money[USD](50.0)
total = usd1.add(usd2)
# This will fail at type-check time (e.g., with mypy)
# eur1 = Money[EUR](200.0)
# total = usd1.add(eur1)
🧠 Notes
This approach is not a substitute for runtime validation, but it's ideal for static type checking.
Phantom types in Python are more of a convention than a language feature, but the typing module makes it very expressive.
For full runtime safety, consider using a library like pydantic or dataclasses.