Phantom types are a type system technique often used in statically typed languages (like Haskell, Scala, or Rust) to encode extra type information that doesn't exist at runtime but helps the compiler catch errors. Python is dynamically typed, so it doesn't have built-in phantom types, but with type hints and generics (via typing module), you can simulate phantom types to some extent for static type checkers like mypy.
Goal:
Implement a type-safe money class in Python that prevents mixing different currencies accidentally, using phantom types to encode the currency at the type level.
Step-by-step example
1. Define phantom types for currencies
We create empty classes to represent currencies. These classes are never instantiated; they only serve as type markers.
python
from typing import TypeVar, Generic, Type
class USD: ...
class EUR: ...
class JPY: ...
2. Define a generic Money class parameterized by the currency phantom type