A Python library for creating phantom types that enforce runtime and static type constraints through predicates.
Phantom-types is a Python library that implements phantom types, allowing developers to create custom types with runtime predicates that enforce specific constraints. It solves the problem of scattered validation logic by making illegal states unrepresentable and promoting type-safe parsing over validation. The library integrates with both static type checkers and runtime validation tools to ensure code correctness.
Python developers building type-safe applications, especially those using pydantic, beartype, or mypy who need to enforce complex runtime constraints through the type system.
Developers choose phantom-types because it uniquely combines static and runtime type enforcement through predicate-based phantom types, reducing validation boilerplate and integrating seamlessly with popular Python tools like pydantic and beartype.
Phantom types for Python.
Open-Awesome is built by the community, for the community. Submit a project, suggest an awesome list, or help improve the catalog on GitHub.
Enables defining custom types with runtime predicates, making illegal states unrepresentable as demonstrated in the Name class example with contained predicate.
Seamlessly works with beartype and typeguard for design-by-contract pre- and post-conditions, shown in the soon function with TZAware type.
Offers ready-to-use support for pydantic validation and JSONSchema output, as illustrated in the Person model example with custom schema formatting.
Integrates with mypy to catch type errors during development, enhancing code reliability through static analysis, noted in the type checking examples.
Requires installing extras like dateutil or phonenumbers for certain features, adding complexity to dependency handling and increasing project bloat.
Predicate evaluation at runtime introduces slowdowns, which may not be suitable for performance-critical applications where speed is prioritized.
Phantom types and 'Parse, don't validate' require understanding advanced type system patterns, which can be challenging for teams new to these concepts.