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

core-parsing-formatting.mddocs/

Core Parsing and Formatting

Essential functions for parsing phone number strings into structured objects and formatting them for display or storage. These functions form the foundation of phonenumberslite's functionality.

Capabilities

Phone Number Parsing

Parse phone number strings with various input formats, handling international prefixes, national formats, and region-specific patterns.

def parse(number: str, region: str = None, keep_raw_input: bool = False, 
          numobj: PhoneNumber = None, _check_region: bool = True) -> PhoneNumber:
    """
    Parse a phone number string and return a PhoneNumber object.
    
    Parameters:
    - number: The phone number string to parse
    - region: Two-letter region code (ISO 3166-1 alpha-2) for context when parsing national numbers
    - keep_raw_input: Whether to store the raw input string in the PhoneNumber object
    - numobj: Optional PhoneNumber object to reuse instead of creating new one
    - _check_region: Internal parameter for region validation (default True)
    
    Returns:
    PhoneNumber object with parsed components
    
    Raises:
    NumberParseException: If number cannot be parsed
    """

Usage Examples:

import phonenumbers

# Parse international number with country code
number = phonenumbers.parse("+442083661177")

# Parse national number with region context
uk_number = phonenumbers.parse("020 8366 1177", "GB")

# Parse with raw input preservation
number_with_raw = phonenumbers.parse("+44 (20) 8366-1177", keep_raw_input=True)

# Handle parsing errors
try:
    invalid = phonenumbers.parse("invalid", "US")
except phonenumbers.NumberParseException as e:
    print(f"Parse error: {e}")

Standard Number Formatting

Format parsed phone numbers using standard international formats for display, storage, or dialing purposes.

def format_number(numobj: PhoneNumber, num_format: PhoneNumberFormat) -> str:
    """
    Format a phone number according to the specified format.
    
    Parameters:
    - numobj: PhoneNumber object to format
    - num_format: Formatting style (E164, INTERNATIONAL, NATIONAL, RFC3966)
    
    Returns:
    Formatted phone number string
    """

Usage Examples:

import phonenumbers
from phonenumbers import PhoneNumberFormat

number = phonenumbers.parse("+442083661177")

# E164 format (for storage/APIs)
e164 = phonenumbers.format_number(number, PhoneNumberFormat.E164)
# "+442083661177"

# International format (for international display)
intl = phonenumbers.format_number(number, PhoneNumberFormat.INTERNATIONAL)
# "+44 20 8366 1177"

# National format (for domestic display)
national = phonenumbers.format_number(number, PhoneNumberFormat.NATIONAL)
# "020 8366 1177"

# RFC3966 format (for tel: URIs)
rfc = phonenumbers.format_number(number, PhoneNumberFormat.RFC3966)
# "tel:+44-20-8366-1177"

Custom Pattern Formatting

Format numbers using custom formatting patterns for specialized display requirements.

def format_by_pattern(numobj: PhoneNumber, num_format: PhoneNumberFormat, 
                     user_defined_formats: list) -> str:
    """
    Format a number using user-defined formatting patterns.
    
    Parameters:
    - numobj: PhoneNumber object to format
    - num_format: Base formatting style
    - user_defined_formats: List of NumberFormat objects with custom patterns
    
    Returns:
    Formatted number string using custom patterns
    """

Original Format Preservation

Format numbers while attempting to preserve the original formatting structure when possible.

def format_in_original_format(numobj: PhoneNumber, region_calling_from: str) -> str:
    """
    Format number preserving original formatting where possible.
    
    Parameters:
    - numobj: PhoneNumber object (must have been parsed with keep_raw_input=True)
    - region_calling_from: Region code for formatting context
    
    Returns:
    Number formatted to match original input structure
    """

Carrier Code Formatting

Format national numbers with carrier code information for regions that support carrier selection.

def format_national_number_with_carrier_code(numobj: PhoneNumber, 
                                           carrier_code: str) -> str:
    """
    Format national number including carrier code.
    
    Parameters:
    - numobj: PhoneNumber object to format
    - carrier_code: Carrier code to include in formatting
    
    Returns:
    National format string with carrier code
    """

def format_national_number_with_preferred_carrier_code(numobj: PhoneNumber, 
                                                     fallback_carrier_code: str) -> str:
    """
    Format using preferred carrier code or fallback.
    
    Parameters:
    - numobj: PhoneNumber with potential preferred carrier code
    - fallback_carrier_code: Carrier code to use if none preferred
    
    Returns:
    National format with appropriate carrier code
    """

Mobile Dialing Format

Format numbers optimized for mobile dialing from specific regions, handling international prefixes and local conventions.

def format_number_for_mobile_dialing(numobj: PhoneNumber, region_calling_from: str, 
                                   with_formatting: bool = False) -> str:
    """
    Format number for mobile dialing from specified region.
    
    Parameters:
    - numobj: PhoneNumber to format for dialing
    - region_calling_from: Region from which the call will be made
    - with_formatting: Whether to include spacing and punctuation
    
    Returns:
    Number formatted for mobile dialing, or empty string if not dialable
    """

International Dialing Format

Format numbers for dialing from international locations, handling various international prefix patterns.

def format_out_of_country_calling_number(numobj: PhoneNumber, 
                                       region_calling_from: str) -> str:
    """
    Format number for international dialing from specified region.
    
    Parameters:
    - numobj: PhoneNumber to format
    - region_calling_from: Region code for the calling location
    
    Returns:
    Number formatted with appropriate international prefix
    """

def format_out_of_country_keeping_alpha_chars(numobj: PhoneNumber, 
                                            region_calling_from: str) -> str:
    """
    Format for international dialing while preserving alpha characters.
    
    Parameters:
    - numobj: PhoneNumber containing alpha characters
    - region_calling_from: Calling region code
    
    Returns:
    Formatted number retaining alpha characters where appropriate
    """

Usage Patterns

Basic Parsing and Formatting Workflow

import phonenumbers
from phonenumbers import PhoneNumberFormat

# Parse various input formats
numbers = [
    "+1-800-555-1234",      # International with formatting
    "800.555.1234",         # National with dots
    "(800) 555-1234",       # National with parentheses
    "18005551234",          # International without formatting
]

for number_string in numbers:
    try:
        # Parse with US context for national numbers
        parsed = phonenumbers.parse(number_string, "US")
        
        # Format for different purposes
        for_storage = phonenumbers.format_number(parsed, PhoneNumberFormat.E164)
        for_display = phonenumbers.format_number(parsed, PhoneNumberFormat.INTERNATIONAL)
        
        print(f"Input: {number_string}")
        print(f"Storage: {for_storage}")
        print(f"Display: {for_display}")
        print()
        
    except phonenumbers.NumberParseException as e:
        print(f"Failed to parse {number_string}: {e}")

Regional Context Handling

import phonenumbers

# Same number string, different regional contexts
national_number = "020 8366 1177"

# Parse as UK number
uk_number = phonenumbers.parse(national_number, "GB")
print(f"UK: {phonenumbers.format_number(uk_number, PhoneNumberFormat.E164)}")

# Parsing without region context would fail for national format
try:
    no_region = phonenumbers.parse(national_number, None)
except phonenumbers.NumberParseException:
    print("National number requires region context")

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