Phone Numbers
The pydantic_extra_types.phone_numbers module provides the PhoneNumber data type.
This class depends on the phonenumbers package, which is a Python port of Google’s libphonenumber.
PhoneNumber
Section titled “PhoneNumber”Bases: str
A wrapper around the phonenumbers.PhoneNumber object.
It provides class-level configuration points you can change by subclassing:
Examples
Section titled “Examples”Normal usage:
Section titled “Normal usage:”from pydantic import BaseModel
from pydantic_extra_types.phone_numbers import PhoneNumber
class Contact(BaseModel):
name: str
phone: PhoneNumber
c = Contact(name='Alice', phone='+1 650-253-0000')
print(c.phone)
# > tel:+1-650-253-0000 (formatted using RFC3966 by default)Changing defaults by subclassing:
Section titled “Changing defaults by subclassing:”from pydantic_extra_types.phone_numbers import PhoneNumber
class USPhone(PhoneNumber):
default_region_code = 'US'
supported_regions = ['US']
phone_format = 'NATIONAL'
# Now parsing will accept national numbers for the US
p = USPhone('650-253-0000')
print(p)
# > 650-253-0000Changing defaults by using the provided validator annotation:
Section titled “Changing defaults by using the provided validator annotation:”from typing import Annotated, Union
import phonenumbers
from pydantic import BaseModel
from pydantic_extra_types.phone_numbers import PhoneNumberValidator
E164NumberType = Annotated[Union[str, phonenumbers.PhoneNumber], PhoneNumberValidator(number_format='E164')]
class Model(BaseModel):
phone: E164NumberType
m = Model(phone='+1 650-253-0000')
print(m.phone)
# > +16502530000Attributes
Section titled “Attributes”default_region_code
Section titled “default_region_code”The default region code to use when parsing phone numbers without an international prefix.
Type: str | None Default: None
supported_regions
Section titled “supported_regions”The supported regions. If empty, all regions are supported.
phone_format
Section titled “phone_format”The format of the phone number.
Type: str Default: 'RFC3966'
PhoneNumberValidator
Section titled “PhoneNumberValidator”An annotation to validate phonenumbers.PhoneNumber objects.
Attributes
Section titled “Attributes”default_region
Section titled “default_region”The default region code to use when parsing phone numbers without an international prefix.
If None (the default), the region must be supplied in the phone number as an international prefix.
Type: str | None Default: None
number_format
Section titled “number_format”The format of the phone number to return. See phonenumbers.PhoneNumberFormat for valid values.
Type: str Default: 'RFC3966'
supported_regions
Section titled “supported_regions”The supported regions. If empty (the default), all regions are supported.
Type: Sequence[str] | None Default: None
Was this page helpful?