Pydantic Support#

phantom-types supports pydantic out of the box by providing a __get_validators__() hook on the base Phantom class. Most of the shipped types also implements full JSON Schema and OpenAPI support.

To make a phantom type compatible with pydantic, all you need to do is override Phantom.__schema__():

from phantom import Phantom
from phantom.schema import Schema

class Name(str, Phantom, predicate=...):
    def __schema__(cls) -> Schema:
        return super().__schema__() | Schema(
            description="A type for names",

As can be seen in the example, __schema__() implementations are expected to return a dict extending its super().__schema__(), however this is not a requirement and any Schema-compatible dict can be returned.