|
26 | 26 |
|
27 | 27 |
|
28 | 28 | class PhoneNumber(str): |
29 | | - """A wrapper around the `phonenumbers.PhoneNumber` object.""" |
| 29 | + """A wrapper around the `phonenumbers.PhoneNumber` object. |
| 30 | +
|
| 31 | + It provides class-level configuration points you can change by subclassing: |
| 32 | +
|
| 33 | + ## Examples |
| 34 | +
|
| 35 | + ### Normal usage: |
| 36 | +
|
| 37 | + ```python |
| 38 | + from pydantic import BaseModel |
| 39 | + from pydantic_extra_types.phone_numbers import PhoneNumber |
| 40 | +
|
| 41 | + class Contact(BaseModel): |
| 42 | + name: str |
| 43 | + phone: PhoneNumber |
| 44 | +
|
| 45 | + c = Contact(name='Alice', phone='+1 650-253-0000') |
| 46 | + print(c.phone) |
| 47 | + >> tel:+1-650-253-0000 (formatted using RFC3966 by default) |
| 48 | + ``` |
| 49 | +
|
| 50 | + ### Changing defaults by subclassing: |
| 51 | +
|
| 52 | + ```python |
| 53 | + from pydantic_extra_types.phone_numbers import PhoneNumber |
| 54 | +
|
| 55 | + class USPhone(PhoneNumber): |
| 56 | + default_region_code = 'US' |
| 57 | + supported_regions = ['US'] |
| 58 | + phone_format = 'NATIONAL' |
| 59 | +
|
| 60 | + # Now parsing will accept national numbers for the US |
| 61 | + p = USPhone('650-253-0000') |
| 62 | + print(p) |
| 63 | + >> 650-253-0000 |
| 64 | + ``` |
| 65 | +
|
| 66 | + ### Changing defaults by using the provided validator annotation: |
| 67 | +
|
| 68 | + ```python |
| 69 | + from typing import Annotated, Union |
| 70 | + import phonenumbers |
| 71 | + from pydantic import BaseModel |
| 72 | + from pydantic_extra_types.phone_numbers import PhoneNumberValidator |
| 73 | +
|
| 74 | + E164NumberType = Annotated[ |
| 75 | + Union[str, phonenumbers.PhoneNumber], PhoneNumberValidator(number_format="E164") |
| 76 | + ] |
| 77 | +
|
| 78 | +
|
| 79 | + class Model(BaseModel): |
| 80 | + phone: E164NumberType |
| 81 | +
|
| 82 | +
|
| 83 | + m = Model(phone="+1 650-253-0000") |
| 84 | + print(m.phone) |
| 85 | + >> +16502530000 |
| 86 | + ``` |
| 87 | +
|
| 88 | + """ |
30 | 89 |
|
31 | 90 | default_region_code: ClassVar[str | None] = None |
32 | 91 | """The default region code to use when parsing phone numbers without an international prefix.""" |
|
0 commit comments