Pydantic Extra Types
Pydantic Extra Types extends Pydantic with specialized data types for various common use cases, such as `Color`, `PhoneNumber`, `Country`, `ULID`, and `SemanticVersion`. It is currently at version 2.11.1 and receives frequent updates, often with monthly or bi-monthly patch and minor releases, adding new types and features.
Warnings
- breaking When migrating from Pydantic V1 to V2, types like `Color` and `PaymentCardNumber` were moved out of the main `pydantic` library into `pydantic-extra-types`. Direct imports from `pydantic.color` or `pydantic.payment` will no longer work.
- deprecated The previous `semver` module, which relied on the external `python-semver` package, has been deprecated in `v2.10.0`. It was replaced by an internal `SemanticVersion` type.
- gotcha Many specialized types within `pydantic-extra-types` require additional optional dependencies to be installed. For example, `PhoneNumber` requires `phonenumbers`, `Country` types require `pycountry`, and `PendulumDuration` requires `pendulum`. Simply installing `pydantic-extra-types` without specifying extras will lead to `ModuleNotFoundError` when these types are used.
- gotcha Most types are not directly available from the top-level `pydantic_extra_types` package but are nested within submodules. For instance, `Color` is in `pydantic_extra_types.color`, and `PhoneNumber` is in `pydantic_extra_types.phone_numbers`. Attempting `from pydantic_extra_types import Color` will result in an `ImportError`.
Install
-
pip install pydantic-extra-types -
pip install "pydantic-extra-types[all]" -
pip install "pydantic-extra-types[phonenumbers,pendulum,pycountry]"
Imports
- Color
from pydantic_extra_types.color import Color
- PhoneNumber
from pydantic_extra_types.phone_numbers import PhoneNumber
- CountryAlpha2
from pydantic_extra_types.country import CountryAlpha2
- SemanticVersion
from pydantic_extra_types.semantic_version import SemanticVersion
Quickstart
from pydantic import BaseModel, ValidationError
from pydantic_extra_types.phone_numbers import PhoneNumber
class Contact(BaseModel):
name: str
phone: PhoneNumber
try:
# Valid phone number
c = Contact(name='Alice', phone='+1 650-253-0000')
print(c.phone.e164) # Outputs: +16502530000 (formatted by default as RFC3966 or E164, depending on version/config)
# Invalid phone number
Contact(name='Bob', phone='not-a-phone-number')
except ValidationError as e:
print(f"Validation error: {e}")