phone-iso3166
raw JSON → 0.4.1 verified Fri May 01 auth: no python
A Python library that maps phone numbers (E.164 format) to their corresponding country codes (ISO 3166-1 alpha-2). Version 0.4.1 provides a simple `CountryCodeResolver` class and a convenience function `phone_country`. Lightweight with no external dependencies.
pip install phone-iso3166 Common errors
error AttributeError: module 'phone_iso3166' has no attribute 'country_code' ↓
cause Incorrect import path or outdated version. The `country_code` function was added in version 0.4.0. If using an older version, it won't exist.
fix
Upgrade to the latest version:
pip install --upgrade phone-iso3166. Use from phone_iso3166 import country_code. error phone_iso3166.exceptions.InvalidPhoneNumber: Invalid phone number format ↓
cause The input phone number is missing the '+' prefix or contains non-numeric characters after the '+'.
fix
Ensure the phone number is in E.164 format with a leading '+' and only digits after that, e.g., '+14155552671'.
Warnings
gotcha Input must be in E.164 format with leading '+'. Without the '+', the library fails silently or returns None. ↓
fix Always include the '+' prefix, e.g., '+14155552671'.
gotcha The library does not validate the phone number's correctness; it only maps based on the country code prefix. Any number starting with '+1' will map to US (or Canada), even if the number is invalid. ↓
fix Use in conjunction with a phone number validation library like `phonenumbers` if you need validation.
deprecated The `CountryCodeResolver` class is functional but the simpler `country_code` function is preferred. The class may be removed in future versions. ↓
fix Use `country_code` function instead of instantiating `CountryCodeResolver`.
Imports
- country_code
from phone_iso3166 import country_code - CountryCodeResolver wrong
from phone_iso3166.resolver import CountryCodeResolvercorrectfrom phone_iso3166 import CountryCodeResolver
Quickstart
from phone_iso3166 import country_code
# Example with a valid US number
phone = '+14155552671'
code = country_code(phone)
print(code) # Output: US
# Example with a UK number
phone2 = '+442071838750'
code2 = country_code(phone2)
print(code2) # Output: GB