Python port of Google's libphonenumber library for parsing, formatting, storing and validating international phone numbers
npx @tessl/cli install tessl/pypi-phonenumbers@9.0.00
# phonenumbers
1
2
A comprehensive Python port of Google's libphonenumber library for parsing, formatting, storing and validating international phone numbers. The library provides extensive functionality including phone number parsing from various formats, validation of phone number correctness, formatting for national and international display, geocoding to determine the geographic location of phone numbers, carrier lookup capabilities, and timezone information extraction.
3
4
## Package Information
5
6
- **Package Name**: phonenumbers
7
- **Language**: Python
8
- **Installation**: `pip install phonenumbers`
9
- **Version**: 9.0.13
10
- **License**: Apache License 2.0
11
12
## Core Imports
13
14
```python
15
import phonenumbers
16
```
17
18
Common imports for specific functionality:
19
20
```python
21
from phonenumbers import parse, format_number, PhoneNumberFormat
22
from phonenumbers import is_valid_number, number_type, PhoneNumberType
23
from phonenumbers import AsYouTypeFormatter
24
```
25
26
## Basic Usage
27
28
```python
29
import phonenumbers
30
from phonenumbers import PhoneNumberFormat
31
32
# Parse a phone number
33
phone_number = phonenumbers.parse("+442083661177", None)
34
35
# Format the number in different ways
36
national = phonenumbers.format_number(phone_number, PhoneNumberFormat.NATIONAL)
37
international = phonenumbers.format_number(phone_number, PhoneNumberFormat.INTERNATIONAL)
38
e164 = phonenumbers.format_number(phone_number, PhoneNumberFormat.E164)
39
40
print(national) # 020 8366 1177
41
print(international) # +44 20 8366 1177
42
print(e164) # +442083661177
43
44
# Validate a phone number
45
is_valid = phonenumbers.is_valid_number(phone_number)
46
print(is_valid) # True
47
48
# Get the number type
49
num_type = phonenumbers.number_type(phone_number)
50
print(num_type) # PhoneNumberType.FIXED_LINE
51
52
# Parse with region context
53
uk_number = phonenumbers.parse("020 8366 1177", "GB")
54
print(phonenumbers.format_number(uk_number, PhoneNumberFormat.E164)) # +442083661177
55
```
56
57
## Architecture
58
59
The phonenumbers library is built around several core components:
60
61
- **PhoneNumber**: Immutable data structure representing a parsed phone number with country code, national number, and metadata
62
- **Parsing Engine**: Robust parser that handles various input formats and regional contexts
63
- **Validation System**: Multi-level validation including format checking, length validation, and carrier verification
64
- **Formatting Engine**: Flexible formatter supporting multiple output formats (E164, national, international)
65
- **Geographic Services**: Integration with location databases for geocoding and timezone lookup
66
- **Carrier Services**: Access to mobile network operator information
67
- **Metadata System**: Comprehensive database of international dialing rules and number patterns
68
69
## Capabilities
70
71
### Core Operations
72
73
Essential phone number operations including parsing from strings, formatting to various output formats, and comprehensive validation. These functions form the foundation of all phone number processing.
74
75
```python { .api }
76
def parse(number: str, region: str | None = None, keep_raw_input: bool = False, numobj: PhoneNumber | None = None) -> PhoneNumber
77
def format_number(numobj: PhoneNumber, num_format: int) -> str
78
def is_valid_number(numobj: PhoneNumber) -> bool
79
def is_possible_number(numobj: PhoneNumber) -> bool
80
def number_type(numobj: PhoneNumber) -> int
81
```
82
83
[Core Operations](./core-operations.md)
84
85
### Geographic Services
86
87
Location-based services including geocoding to determine the geographic region of phone numbers, carrier lookup to identify mobile network operators, and timezone detection for scheduling and localization.
88
89
```python { .api }
90
def region_code_for_number(numobj: PhoneNumber) -> str | None
91
def country_code_for_region(region_code: str) -> int
92
def description_for_number(numobj: PhoneNumber, lang: str, script: str | None = None, region: str | None = None) -> str
93
def name_for_number(numobj: PhoneNumber, lang: str, script: str | None = None, region: str | None = None) -> str
94
def time_zones_for_number(numobj: PhoneNumber) -> tuple[str, ...]
95
```
96
97
[Geographic Services](./geographic-services.md)
98
99
### Short Numbers
100
101
Specialized handling for short numbers including emergency numbers, service numbers, and premium rate numbers. Provides validation and cost information for short dialing codes.
102
103
```python { .api }
104
def is_valid_short_number(numobj: PhoneNumber) -> bool
105
def is_emergency_number(number: str, region_code: str) -> bool
106
def expected_cost(numobj: PhoneNumber) -> int
107
def connects_to_emergency_number(number: str, region_code: str) -> bool
108
```
109
110
[Short Numbers](./short-numbers.md)
111
112
### Text Processing
113
114
Phone number discovery and extraction from unstructured text using configurable matching algorithms. Includes as-you-type formatting for user interfaces.
115
116
```python { .api }
117
class PhoneNumberMatcher:
118
def __init__(self, text: str, region: str | None, leniency: int = Leniency.VALID, max_tries: int = 65535)
119
120
class AsYouTypeFormatter:
121
def __init__(self, region_code: str)
122
def input_digit(self, next_char: str, remember_position: bool = False) -> str
123
```
124
125
[Text Processing](./text-processing.md)
126
127
### Utilities
128
129
Helper functions for string processing, normalization, example number generation, and metadata access. Includes constants and utility functions for advanced use cases.
130
131
```python { .api }
132
def normalize_digits_only(number: str, keep_non_digits: bool = False) -> str
133
def convert_alpha_characters_in_number(number: str) -> str
134
def example_number(region_code: str) -> PhoneNumber | None
135
SUPPORTED_REGIONS: set[str]
136
```
137
138
[Utilities](./utilities.md)
139
140
## Core Types
141
142
```python { .api }
143
class PhoneNumber:
144
"""Represents an international telephone number."""
145
country_code: int | None
146
national_number: int | None
147
extension: str | None
148
italian_leading_zero: bool | None
149
number_of_leading_zeros: int | None
150
raw_input: str | None
151
country_code_source: int
152
preferred_domestic_carrier_code: str | None
153
154
class FrozenPhoneNumber(PhoneNumber):
155
"""Immutable version of PhoneNumber that can be used as dictionary keys."""
156
def __hash__(self) -> int
157
158
class PhoneNumberFormat:
159
"""Output formats for phone numbers."""
160
E164 = 0 # +442083661177
161
INTERNATIONAL = 1 # +44 20 8366 1177
162
NATIONAL = 2 # 020 8366 1177
163
RFC3966 = 3 # tel:+44-20-8366-1177
164
165
class PhoneNumberType:
166
"""Types of phone numbers."""
167
FIXED_LINE = 0
168
MOBILE = 1
169
FIXED_LINE_OR_MOBILE = 2
170
TOLL_FREE = 3
171
PREMIUM_RATE = 4
172
SHARED_COST = 5
173
VOIP = 6
174
PERSONAL_NUMBER = 7
175
PAGER = 8
176
UAN = 9
177
VOICEMAIL = 10
178
UNKNOWN = 99
179
180
class CountryCodeSource:
181
"""Source from which a country code is derived."""
182
UNSPECIFIED = 0
183
FROM_NUMBER_WITH_PLUS_SIGN = 1
184
FROM_NUMBER_WITH_IDD = 5
185
FROM_NUMBER_WITHOUT_PLUS_SIGN = 10
186
FROM_DEFAULT_COUNTRY = 20
187
188
class ValidationResult:
189
"""Results of phone number possibility validation."""
190
IS_POSSIBLE = 0
191
IS_POSSIBLE_LOCAL_ONLY = 4
192
INVALID_COUNTRY_CODE = 1
193
TOO_SHORT = 2
194
INVALID_LENGTH = 5
195
TOO_LONG = 3
196
197
class MatchType:
198
"""Types of number matching results."""
199
NOT_A_NUMBER = 0
200
NO_MATCH = 1
201
SHORT_NSN_MATCH = 2
202
NSN_MATCH = 3
203
EXACT_MATCH = 4
204
205
class NumberParseException(Exception):
206
"""Exception thrown when phone number parsing fails."""
207
INVALID_COUNTRY_CODE = 0
208
NOT_A_NUMBER = 1
209
TOO_SHORT_AFTER_IDD = 2
210
TOO_SHORT_NSN = 3
211
TOO_LONG = 4
212
213
error_type: int
214
_msg: str
215
```