CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-phonenumberslite

Python library for parsing, formatting, storing and validating international phone numbers with reduced memory footprint

Pending
Overview
Eval results
Files

region-metadata.mddocs/

Region and Metadata

Functions for working with country codes, region codes, and geographical information. These functions provide access to supported regions, calling codes, number type information, and regional numbering plan data.

Capabilities

Country Code Operations

Work with country calling codes and their relationships to geographic regions.

def country_code_for_region(region_code: str) -> int:
    """
    Get the country calling code for a region.
    
    Parameters:
    - region_code: Two-letter region code (ISO 3166-1 alpha-2)
    
    Returns:
    Country calling code as integer, or 0 if region not supported
    """

def country_code_for_valid_region(region_code: str) -> int:
    """
    Get country calling code for a region, raising exception if invalid.
    
    Parameters:
    - region_code: Two-letter region code
    
    Returns:
    Country calling code as integer
    
    Raises:
    Exception if region code is not supported
    """

Usage Examples:

import phonenumbers

# Get country codes for regions
us_code = phonenumbers.country_code_for_region("US")
print(f"US country code: +{us_code}")  # +1

uk_code = phonenumbers.country_code_for_region("GB")
print(f"UK country code: +{uk_code}")  # +44

# Handle invalid regions
invalid_code = phonenumbers.country_code_for_region("XX")
print(f"Invalid region code: {invalid_code}")  # 0

Region Code Lookup

Determine which regions are associated with specific country calling codes.

def region_code_for_country_code(country_calling_code: int) -> str:
    """
    Get the main region code for a country calling code.
    
    For country codes shared by multiple regions, returns the main region.
    
    Parameters:
    - country_calling_code: Country calling code to look up
    
    Returns:
    Two-letter region code, or 'ZZ' if not found
    """

def region_codes_for_country_code(country_calling_code: int) -> list:
    """
    Get all region codes that use a specific country calling code.
    
    Parameters:
    - country_calling_code: Country calling code to look up
    
    Returns:
    List of two-letter region codes, empty if none found
    """

def region_code_for_number(numobj: PhoneNumber) -> str:
    """
    Get the region code for a specific phone number.
    
    Parameters:
    - numobj: PhoneNumber object to analyze
    
    Returns:
    Two-letter region code, or None if cannot be determined
    """

Usage Examples:

import phonenumbers

# Single region for country code
main_region = phonenumbers.region_code_for_country_code(44)
print(f"Main region for +44: {main_region}")  # GB

# Multiple regions sharing a country code
nanpa_regions = phonenumbers.region_codes_for_country_code(1)
print(f"NANPA regions: {nanpa_regions}")  # ['US', 'CA', 'AG', 'AI', ...]

# Region for specific number
number = phonenumbers.parse("+442083661177")
region = phonenumbers.region_code_for_number(number)
print(f"Number region: {region}")  # GB

Supported Regions and Codes

Access comprehensive lists of supported regions and country codes.

def supported_regions() -> set:
    """
    Get all supported region codes.
    
    Returns:
    Set of two-letter region codes supported by the library
    """

def supported_calling_codes() -> set:
    """
    Get all supported country calling codes.
    
    Returns:
    Set of integer country calling codes supported by the library
    """

Usage Examples:

import phonenumbers

# Get all supported regions
regions = phonenumbers.supported_regions()
print(f"Number of supported regions: {len(regions)}")
print(f"Sample regions: {sorted(list(regions))[:10]}")

# Get all supported country codes
calling_codes = phonenumbers.supported_calling_codes()
print(f"Number of calling codes: {len(calling_codes)}")
print(f"Sample codes: {sorted(list(calling_codes))[:10]}")

Number Type Support by Region

Determine which types of phone numbers are supported in specific regions.

def supported_types_for_region(region_code: str) -> set:
    """
    Get phone number types supported by a region.
    
    Parameters:
    - region_code: Two-letter region code to check
    
    Returns:
    Set of PhoneNumberType values supported in the region
    """

def supported_types_for_non_geo_entity(country_calling_code: int) -> set:
    """
    Get supported number types for non-geographical entities.
    
    Parameters:
    - country_calling_code: Country code for non-geographical entity
    
    Returns:
    Set of PhoneNumberType values supported
    """

Usage Examples:

import phonenumbers
from phonenumbers import PhoneNumberType

# Check supported types for a region
us_types = phonenumbers.supported_types_for_region("US")
print(f"US supports {len(us_types)} number types")

if PhoneNumberType.MOBILE in us_types:
    print("US supports mobile numbers")

if PhoneNumberType.TOLL_FREE in us_types:
    print("US supports toll-free numbers")

# Non-geographical entities (like satellite services)
satellite_types = phonenumbers.supported_types_for_non_geo_entity(881)
print(f"Satellite service types: {satellite_types}")

Example Numbers

Generate example phone numbers for regions and number types, useful for testing and documentation.

def example_number(region_code: str) -> PhoneNumber:
    """
    Get an example phone number for a region.
    
    Parameters:
    - region_code: Two-letter region code
    
    Returns:
    PhoneNumber object with example number, or None if not available
    """

def example_number_for_type(region_code: str, phone_type: PhoneNumberType) -> PhoneNumber:
    """
    Get an example phone number for a specific region and type.
    
    Parameters:
    - region_code: Two-letter region code
    - phone_type: Type of number desired
    
    Returns:
    PhoneNumber object with example number, or None if not available
    """

def example_number_for_non_geo_entity(country_calling_code: int) -> PhoneNumber:
    """
    Get example number for non-geographical entity.
    
    Parameters:
    - country_calling_code: Country code for non-geographical service
    
    Returns:
    PhoneNumber object with example number, or None if not available
    """

def invalid_example_number(region_code: str) -> PhoneNumber:
    """
    Get an example of an invalid number for a region.
    
    Useful for testing validation logic.
    
    Parameters:
    - region_code: Two-letter region code
    
    Returns:
    PhoneNumber object that is invalid for the region
    """

Usage Examples:

import phonenumbers
from phonenumbers import PhoneNumberType, PhoneNumberFormat

# Get general example for region
us_example = phonenumbers.example_number("US")
if us_example:
    formatted = phonenumbers.format_number(us_example, PhoneNumberFormat.INTERNATIONAL)
    print(f"US example: {formatted}")

# Get specific type examples
uk_mobile = phonenumbers.example_number_for_type("GB", PhoneNumberType.MOBILE)
if uk_mobile:
    formatted = phonenumbers.format_number(uk_mobile, PhoneNumberFormat.INTERNATIONAL)
    print(f"UK mobile example: {formatted}")

uk_toll_free = phonenumbers.example_number_for_type("GB", PhoneNumberType.TOLL_FREE)
if uk_toll_free:
    formatted = phonenumbers.format_number(uk_toll_free, PhoneNumberFormat.INTERNATIONAL)
    print(f"UK toll-free example: {formatted}")

# Invalid example for testing
invalid = phonenumbers.invalid_example_number("US")
if invalid:
    print(f"Invalid US number: {invalid}")
    print(f"Is valid: {phonenumbers.is_valid_number(invalid)}")

National Dialing Prefixes

Access information about national dialing prefixes used within countries.

def ndd_prefix_for_region(region_code: str) -> str:
    """
    Get the national direct dialing (trunk) prefix for a region.
    
    This is the prefix (like '0' in UK, '1' in Russia) that must be
    dialed before area codes when calling within the country.
    
    Parameters:
    - region_code: Two-letter region code
    
    Returns:
    National dialing prefix string, or None if not applicable
    """

Non-Geographical Regions

Work with special country codes that don't correspond to geographic regions.

COUNTRY_CODES_FOR_NON_GEO_REGIONS: set
    """
    Set of country calling codes for non-geographical entities.
    
    These are codes like 800 (International Freephone), 
    881-888 (Global Mobile Satellite System), etc.
    """

Constants

Core Region Constants

Essential constants for working with region codes and country calling codes.

COUNTRY_CODE_TO_REGION_CODE: dict
    """
    Map from country calling codes to region codes.
    
    Key: Country calling code (int)
    Value: Tuple of region codes (str) that use this calling code
    """

SUPPORTED_REGIONS: set
    """
    Set of all supported two-letter region codes (ISO 3166-1 alpha-2).
    
    Includes all regions with defined phone number metadata.
    """

UNKNOWN_REGION: str
    """
    Region code used for unknown or unspecified regions ("ZZ").
    """

COUNTRY_CODES_FOR_NON_GEO_REGIONS: set
    """
    Set of country calling codes for non-geographical entities.
    
    These are codes like 800 (International Freephone), 
    881-888 (Global Mobile Satellite System), etc.
    """

NON_DIGITS_PATTERN: Pattern
    """
    Compiled regular expression pattern matching non-digit characters.
    
    Used for normalizing phone number strings.
    """

Short Number Constants

SUPPORTED_SHORT_REGIONS: list
    """
    List of region codes that support short number processing.
    
    Short numbers include emergency numbers, service codes, etc.
    """

REGION_CODE_FOR_NON_GEO_ENTITY: str
    """
    Special region code for non-geographical entities ("001").
    """

Usage Patterns

Region Information Lookup

import phonenumbers
from phonenumbers import PhoneNumberType

def get_region_info(region_code):
    """Get comprehensive information about a region's numbering plan."""
    if region_code not in phonenumbers.supported_regions():
        return {"error": f"Region {region_code} not supported"}
    
    country_code = phonenumbers.country_code_for_region(region_code)
    supported_types = phonenumbers.supported_types_for_region(region_code)
    ndd_prefix = phonenumbers.ndd_prefix_for_region(region_code)
    
    # Get example numbers for each supported type
    examples = {}
    for phone_type in supported_types:
        example = phonenumbers.example_number_for_type(region_code, phone_type)
        if example:
            examples[phone_type] = phonenumbers.format_number(
                example, phonenumbers.PhoneNumberFormat.INTERNATIONAL
            )
    
    return {
        'region_code': region_code,
        'country_code': country_code,
        'ndd_prefix': ndd_prefix,
        'supported_types': list(supported_types),
        'examples': examples,
        'is_nanpa': phonenumbers.is_nanpa_country(region_code)
    }

# Example usage
us_info = get_region_info("US")
print(f"US country code: +{us_info['country_code']}")
print(f"US trunk prefix: {us_info['ndd_prefix']}")
print(f"Supported types: {len(us_info['supported_types'])}")
for phone_type, example in us_info['examples'].items():
    print(f"  {phone_type}: {example}")

Multi-Region Analysis

import phonenumbers

def analyze_shared_country_codes():
    """Find country codes shared by multiple regions."""
    shared_codes = {}
    
    for code in phonenumbers.supported_calling_codes():
        regions = phonenumbers.region_codes_for_country_code(code)
        if len(regions) > 1:
            shared_codes[code] = regions
    
    return shared_codes

def find_regions_by_criteria(has_mobile=True, has_toll_free=False):
    """Find regions that meet specific numbering criteria."""
    matching_regions = []
    
    for region in phonenumbers.supported_regions():
        supported_types = phonenumbers.supported_types_for_region(region)
        
        meets_criteria = True
        
        if has_mobile and PhoneNumberType.MOBILE not in supported_types:
            meets_criteria = False
        
        if has_toll_free and PhoneNumberType.TOLL_FREE not in supported_types:
            meets_criteria = False
        
        if meets_criteria:
            matching_regions.append(region)
    
    return matching_regions

# Example usage
shared = analyze_shared_country_codes()
print(f"Country codes shared by multiple regions: {len(shared)}")
for code, regions in list(shared.items())[:5]:
    print(f"  +{code}: {regions}")

mobile_regions = find_regions_by_criteria(has_mobile=True)
print(f"Regions with mobile support: {len(mobile_regions)}")

Testing Data Generation

import phonenumbers
from phonenumbers import PhoneNumberType, PhoneNumberFormat

def generate_test_numbers(region_code, count_per_type=2):
    """Generate test phone numbers for a region."""
    test_data = {
        'region': region_code,
        'country_code': phonenumbers.country_code_for_region(region_code),
        'valid_numbers': {},
        'invalid_numbers': []
    }
    
    # Get supported types
    supported_types = phonenumbers.supported_types_for_region(region_code)
    
    # Generate valid examples for each type
    for phone_type in supported_types:
        examples = []
        for i in range(count_per_type):
            example = phonenumbers.example_number_for_type(region_code, phone_type)
            if example:
                examples.append({
                    'e164': phonenumbers.format_number(example, PhoneNumberFormat.E164),
                    'international': phonenumbers.format_number(example, PhoneNumberFormat.INTERNATIONAL),
                    'national': phonenumbers.format_number(example, PhoneNumberFormat.NATIONAL)
                })
        
        if examples:
            test_data['valid_numbers'][phone_type] = examples
    
    # Generate invalid examples
    invalid_example = phonenumbers.invalid_example_number(region_code)
    if invalid_example:
        test_data['invalid_numbers'].append({
            'number': invalid_example,
            'formatted': phonenumbers.format_number(invalid_example, PhoneNumberFormat.INTERNATIONAL),
            'is_valid': phonenumbers.is_valid_number(invalid_example)
        })
    
    return test_data

# Example usage
test_data = generate_test_numbers("GB", count_per_type=1)
print(f"Test data for {test_data['region']} (+{test_data['country_code']}):")
for phone_type, examples in test_data['valid_numbers'].items():
    print(f"  {phone_type}: {examples[0]['international']}")

Install with Tessl CLI

npx tessl i tessl/pypi-phonenumberslite

docs

as-you-type-formatting.md

core-parsing-formatting.md

index.md

number-validation.md

phone-number-matching.md

region-metadata.md

short-numbers.md

utility-functions.md

tile.json