Phantom Types for Python

3.0.2 · active · verified Thu Apr 16

phantom-types is a Python library that enables the creation of 'phantom types' to enforce type safety at compile time without incurring runtime overhead. It leverages Python's `__instancecheck__` protocol and boolean predicates to allow developers to define stricter type constraints, helping to make 'illegal states unrepresentable' and mitigate 'shotgun parsing'. The library is currently at version 3.0.2 and follows semantic versioning after its 1.0 release, with new versions released periodically to add features, fix bugs, and maintain compatibility.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to define a simple phantom type `Name` that narrows the `str` type to only accept specific values ('Jane' or 'Joe'). It shows both explicit parsing using `Name.parse()` and leveraging Python's `isinstance()` for type narrowing recognized by static type checkers. Invalid inputs are caught at compile time by type checkers, preventing runtime errors.

from phantom import Phantom
from phantom.predicates.collection import contained
from typing import TYPE_CHECKING

# Define a phantom type 'Name' that only accepts 'Jane' or 'Joe'
class Name(str, Phantom, predicate=contained({"Jane", "Joe"})):
    pass

def greet(name: Name):
    print(f"Hello {name}!")

# Valid usage: explicitly parsing a value into the phantom type
greet(Name.parse("Jane"))

# Valid usage: using runtime type checking (e.g., isinstance) to narrow the type
joe = "Joe"
assert isinstance(joe, Name) # This assertion informs type checkers
greet(joe)

# This call would typically be caught by a static type checker like MyPy
# as 'bird' does not satisfy the predicate for 'Name'.
# if TYPE_CHECKING:
#     greet("bird") # E.g., Uncommenting this line would cause a MyPy error

view raw JSON →