Python-phonenumbers is a Python port of Google's `libphonenumber` library, providing robust functionality for parsing, formatting, storing, and validating international phone numbers. It is actively maintained and regularly updated to reflect upstream changes from the original Java library. The current version is 9.0.26.
pip install phonenumbersVerified import paths — ran on the pinned version, not inferred.
This quickstart demonstrates how to parse, validate, format, and retrieve auxiliary information (carrier, region, timezone) for a phone number. It handles potential parsing errors using a try-except block.
Always provide a valid default region code (e.g., 'US', 'GB') when parsing numbers that are not in E.164 international format (starting with '+') or wrap parsing calls in a `try-except phonenumbers.NumberParseException` block.
If migrating from versions prior to 8.0.0, ensure that you call `phonenumbers.parse()` first to create a `PhoneNumber` object and pass that object to these methods.
Do not share `PhoneNumberMatcher` instances across multiple threads. Create a new instance for each thread or use appropriate locking mechanisms if sharing is unavoidable.
If memory usage is a critical concern, consider using the `phonenumberslite` variant (`pip install phonenumberslite`), which omits some of the larger metadata packages. Alternatively, be aware of the memory implications and manage them for your application.
Ensure the library is correctly installed using pip: `pip install phonenumbers`. If using a virtual environment, ensure it's activated before installation. Verify the import statement is `import phonenumbers`.
When parsing a national number (without an international dialing code), provide the two-letter ISO 3166-1 alpha-2 country code as the second argument to `phonenumbers.parse()`. For international numbers (starting with '+'), the region code can often be `None`. Example: `phonenumbers.parse('0721234567', 'RO')` or `phonenumbers.parse('+40721234567', None)`.Ensure the input string is a plausible phone number. This error indicates fundamental parsing failure, often requiring pre-validation of user input or a robust `try-except` block to handle malformed strings gracefully. Example: `try: number = phonenumbers.parse(input_string, 'US') except phonenumbers.phonenumberutil.NumberParseException: print('Invalid number format')`.Ensure that subsequent operations requiring a `PhoneNumber` object receive the parsed object, not the formatted string. If you need to re-validate or operate on a formatted number, parse it again into a `PhoneNumber` object. Example: `parsed_number = phonenumbers.parse('+15551234567', 'US'); formatted_string = phonenumbers.format_number(parsed_number, phonenumbers.PhoneNumberFormat.E164); # If you need to validate formatted_string, you must re-parse it: re_parsed_number = phonenumbers.parse(formatted_string, None); is_valid = phonenumbers.is_valid_number(re_parsed_number)`.No dependency data recorded yet.