Python port of Google's libphonenumber library for parsing, formatting, storing and validating international phone numbers
—
Specialized handling for short dialing codes including emergency numbers, service numbers, and premium rate numbers. Short numbers are typically 3-6 digit codes that provide access to specific services and may have regional variations in availability and cost.
Functions to validate short numbers and check their applicability in different regions.
def is_possible_short_number(numobj: PhoneNumber) -> bool:
"""
Check if short number is possible.
Parameters:
- numobj: PhoneNumber representing a short number
Returns:
True if the number could be a valid short number
"""
def is_possible_short_number_for_region(short_numobj: PhoneNumber, region_dialing_from: str) -> bool:
"""
Check if short number is possible when dialing from specified region.
Parameters:
- short_numobj: PhoneNumber representing a short number
- region_dialing_from: Region code from which the number would be dialed
Returns:
True if the short number is possible from the specified region
"""
def is_valid_short_number(numobj: PhoneNumber) -> bool:
"""
Check if short number is valid.
Parameters:
- numobj: PhoneNumber representing a short number
Returns:
True if the short number is valid and operational
"""
def is_valid_short_number_for_region(short_numobj: PhoneNumber, region_dialing_from: str) -> bool:
"""
Check if short number is valid for specified region.
Parameters:
- short_numobj: PhoneNumber representing a short number
- region_dialing_from: Region code from which the number would be dialed
Returns:
True if the short number is valid when dialed from the specified region
"""Usage Examples:
# Parse short numbers (typically without country codes)
emergency_us = phonenumbers.parse("911", "US")
emergency_uk = phonenumbers.parse("999", "GB")
directory_us = phonenumbers.parse("411", "US")
# Check if short numbers are possible
is_911_possible = phonenumbers.is_possible_short_number(emergency_us) # True
is_999_possible = phonenumbers.is_possible_short_number(emergency_uk) # True
# Check validity in specific regions
is_911_valid_us = phonenumbers.is_valid_short_number_for_region(emergency_us, "US") # True
is_911_valid_uk = phonenumbers.is_valid_short_number_for_region(emergency_us, "GB") # False
is_999_valid_uk = phonenumbers.is_valid_short_number_for_region(emergency_uk, "GB") # True
is_999_valid_us = phonenumbers.is_valid_short_number_for_region(emergency_uk, "US") # False
# General validation
is_411_valid = phonenumbers.is_valid_short_number(directory_us) # True
# International short number example
international_toll_free = phonenumbers.parse("800", None) # Some international codes
is_possible_intl = phonenumbers.is_possible_short_number(international_toll_free)Specialized functions for identifying and validating emergency service numbers.
def is_emergency_number(number: str, region_code: str) -> bool:
"""
Check if number is an emergency number in given region.
Parameters:
- number: Phone number string to check
- region_code: Region code for emergency number context
Returns:
True if the number is recognized as an emergency number in the region
"""
def connects_to_emergency_number(number: str, region_code: str) -> bool:
"""
Check if number connects to emergency services.
Parameters:
- number: Phone number string to check
- region_code: Region code for emergency service context
Returns:
True if dialing the number would connect to emergency services
"""Usage Examples:
# Check emergency numbers for different regions
is_911_emergency_us = phonenumbers.is_emergency_number("911", "US") # True
is_112_emergency_us = phonenumbers.is_emergency_number("112", "US") # True (also works in US)
is_999_emergency_uk = phonenumbers.is_emergency_number("999", "GB") # True
is_112_emergency_uk = phonenumbers.is_emergency_number("112", "GB") # True
# Check if numbers connect to emergency services
connects_911 = phonenumbers.connects_to_emergency_number("911", "US") # True
connects_999 = phonenumbers.connects_to_emergency_number("999", "GB") # True
# Invalid emergency numbers
is_123_emergency = phonenumbers.is_emergency_number("123", "US") # False
# Multi-regional emergency codes
is_112_emergency_de = phonenumbers.is_emergency_number("112", "DE") # True (EU standard)
is_112_emergency_fr = phonenumbers.is_emergency_number("112", "FR") # True
# Practical usage: emergency number detection
def is_emergency_call(number_str, region):
"""Helper function to identify emergency calls."""
return (phonenumbers.is_emergency_number(number_str, region) or
phonenumbers.connects_to_emergency_number(number_str, region))
# Test various emergency scenarios
print(is_emergency_call("911", "US")) # True
print(is_emergency_call("112", "DE")) # True
print(is_emergency_call("100", "IN")) # True (police in India)
print(is_emergency_call("123", "US")) # FalseFunctions to determine the cost category and billing implications of short numbers.
def expected_cost(numobj: PhoneNumber) -> int:
"""
Get expected cost category for short number.
Parameters:
- numobj: PhoneNumber representing a short number
Returns:
ShortNumberCost value indicating cost category
"""
def expected_cost_for_region(short_numobj: PhoneNumber, region_dialing_from: str) -> int:
"""
Get expected cost when dialing from specified region.
Parameters:
- short_numobj: PhoneNumber representing a short number
- region_dialing_from: Region code from which the number would be dialed
Returns:
ShortNumberCost value for the specific dialing region
"""Short Number Cost Types:
class ShortNumberCost:
"""Cost categories for short numbers."""
TOLL_FREE = 0 # Free to call
STANDARD_RATE = 1 # Standard local/national rate
PREMIUM_RATE = 2 # Higher than standard rate
UNKNOWN_COST = -1 # Cost information unavailableUsage Examples:
# Check costs for different short numbers
emergency = phonenumbers.parse("911", "US")
directory = phonenumbers.parse("411", "US")
premium = phonenumbers.parse("900", "US") # Premium rate example
# Get cost categories
emergency_cost = phonenumbers.expected_cost(emergency)
directory_cost = phonenumbers.expected_cost(directory)
premium_cost = phonenumbers.expected_cost(premium)
# Interpret cost categories
if emergency_cost == phonenumbers.ShortNumberCost.TOLL_FREE:
print("Emergency calls are free")
elif emergency_cost == phonenumbers.ShortNumberCost.STANDARD_RATE:
print("Emergency calls charged at standard rate")
# Regional cost variations
uk_directory = phonenumbers.parse("118", "GB")
uk_cost = phonenumbers.expected_cost_for_region(uk_directory, "GB")
# Cost checking utility
def describe_cost(short_number, region=None):
"""Describe the cost implications of calling a short number."""
if region:
cost = phonenumbers.expected_cost_for_region(short_number, region)
else:
cost = phonenumbers.expected_cost(short_number)
cost_descriptions = {
phonenumbers.ShortNumberCost.TOLL_FREE: "Free to call",
phonenumbers.ShortNumberCost.STANDARD_RATE: "Standard rate applies",
phonenumbers.ShortNumberCost.PREMIUM_RATE: "Premium rate - higher charges apply",
phonenumbers.ShortNumberCost.UNKNOWN_COST: "Cost information unavailable"
}
return cost_descriptions.get(cost, "Unknown cost category")
# Usage examples
print(describe_cost(emergency)) # "Free to call"
print(describe_cost(directory)) # "Standard rate applies"
print(describe_cost(premium)) # "Premium rate - higher charges apply"Functions to identify short numbers that are specific to particular mobile carriers.
def is_carrier_specific(numobj: PhoneNumber) -> bool:
"""
Check if short number is carrier-specific.
Parameters:
- numobj: PhoneNumber representing a short number
Returns:
True if the short number only works with specific carriers
"""
def is_carrier_specific_for_region(numobj: PhoneNumber, region_dialing_from: str) -> bool:
"""
Check if short number is carrier-specific for region.
Parameters:
- numobj: PhoneNumber representing a short number
- region_dialing_from: Region code for carrier context
Returns:
True if the short number is carrier-specific in the specified region
"""Usage Examples:
# Some short numbers work only with specific carriers
carrier_service = phonenumbers.parse("611", "US") # Customer service (carrier-specific)
universal_service = phonenumbers.parse("911", "US") # Emergency (universal)
# Check carrier specificity
is_611_carrier_specific = phonenumbers.is_carrier_specific(carrier_service) # True
is_911_carrier_specific = phonenumbers.is_carrier_specific(universal_service) # False
# Regional carrier specificity
is_carrier_specific_us = phonenumbers.is_carrier_specific_for_region(carrier_service, "US")
# Practical usage
def check_service_availability(short_number, region):
"""Check if a short number service is universally available."""
if phonenumbers.is_carrier_specific_for_region(short_number, region):
return "Service may not be available on all carriers"
else:
return "Service should work on all carriers"
availability = check_service_availability(carrier_service, "US")
print(availability) # "Service may not be available on all carriers"Functions to identify short numbers that provide SMS or messaging services.
def is_sms_service_for_region(numobj: PhoneNumber, region_dialing_from: str) -> bool:
"""
Check if number is an SMS service in specified region.
Parameters:
- numobj: PhoneNumber representing a short number
- region_dialing_from: Region code for SMS service context
Returns:
True if the number provides SMS services in the specified region
"""Usage Examples:
# Check for SMS services
sms_service = phonenumbers.parse("40404", "US") # Twitter SMS (example)
voice_service = phonenumbers.parse("411", "US") # Directory assistance
# Check if services support SMS
is_sms = phonenumbers.is_sms_service_for_region(sms_service, "US") # True
is_voice_sms = phonenumbers.is_sms_service_for_region(voice_service, "US") # False
# Practical usage for messaging applications
def get_service_type(short_number, region):
"""Determine what type of service a short number provides."""
services = []
if phonenumbers.is_sms_service_for_region(short_number, region):
services.append("SMS")
if phonenumbers.is_emergency_number(
phonenumbers.format_number(short_number, phonenumbers.PhoneNumberFormat.E164),
region
):
services.append("Emergency")
if phonenumbers.is_carrier_specific_for_region(short_number, region):
services.append("Carrier-specific")
return services if services else ["Voice service"]
service_types = get_service_type(sms_service, "US")
print(service_types) # ["SMS"]Information about which regions support short number services.
SUPPORTED_SHORT_REGIONS: list[str] # List of regions with short number supportUsage Examples:
# Check which regions have short number support
supported = phonenumbers.SUPPORTED_SHORT_REGIONS
# Check if a specific region is supported
is_us_supported = "US" in supported # True
is_gb_supported = "GB" in supported # True
# Validate region before processing short numbers
def process_short_number(number_str, region):
"""Process a short number with region validation."""
if region not in phonenumbers.SUPPORTED_SHORT_REGIONS:
return f"Short number support not available for region: {region}"
try:
short_number = phonenumbers.parse(number_str, region)
if phonenumbers.is_valid_short_number_for_region(short_number, region):
cost = phonenumbers.expected_cost_for_region(short_number, region)
is_emergency = phonenumbers.is_emergency_number(number_str, region)
result = {
"valid": True,
"cost_category": cost,
"is_emergency": is_emergency,
"carrier_specific": phonenumbers.is_carrier_specific_for_region(short_number, region)
}
return result
else:
return {"valid": False, "reason": "Invalid short number for region"}
except phonenumbers.NumberParseException as e:
return {"valid": False, "reason": f"Parsing error: {e}"}
# Usage examples
result_911 = process_short_number("911", "US")
# {"valid": True, "cost_category": 0, "is_emergency": True, "carrier_specific": False}
result_611 = process_short_number("611", "US")
# {"valid": True, "cost_category": 1, "is_emergency": False, "carrier_specific": True}
print(f"Supported regions: {len(supported)} regions")
print(f"Sample regions: {supported[:10]}") # First 10 supported regionsCombining multiple short number functions for comprehensive analysis.
Usage Examples:
def analyze_short_number(number_str, region):
"""Comprehensive analysis of a short number."""
if region not in phonenumbers.SUPPORTED_SHORT_REGIONS:
return {"error": f"Region {region} not supported for short numbers"}
try:
short_number = phonenumbers.parse(number_str, region)
analysis = {
"number": number_str,
"region": region,
"is_possible": phonenumbers.is_possible_short_number_for_region(short_number, region),
"is_valid": phonenumbers.is_valid_short_number_for_region(short_number, region),
"is_emergency": phonenumbers.is_emergency_number(number_str, region),
"connects_to_emergency": phonenumbers.connects_to_emergency_number(number_str, region),
"cost_category": phonenumbers.expected_cost_for_region(short_number, region),
"is_carrier_specific": phonenumbers.is_carrier_specific_for_region(short_number, region),
"is_sms_service": phonenumbers.is_sms_service_for_region(short_number, region)
}
# Add cost description
cost_map = {
phonenumbers.ShortNumberCost.TOLL_FREE: "Free",
phonenumbers.ShortNumberCost.STANDARD_RATE: "Standard rate",
phonenumbers.ShortNumberCost.PREMIUM_RATE: "Premium rate",
phonenumbers.ShortNumberCost.UNKNOWN_COST: "Unknown cost"
}
analysis["cost_description"] = cost_map.get(analysis["cost_category"], "Unknown")
return analysis
except phonenumbers.NumberParseException as e:
return {"error": f"Failed to parse '{number_str}': {e}"}
# Analyze various short numbers
emergency_analysis = analyze_short_number("911", "US")
directory_analysis = analyze_short_number("411", "US")
uk_emergency_analysis = analyze_short_number("999", "GB")
print("911 Analysis:", emergency_analysis)
# Output includes: is_emergency=True, cost="Free", carrier_specific=False
print("411 Analysis:", directory_analysis)
# Output includes: is_emergency=False, cost="Standard rate", etc.
# Batch analysis
short_numbers_to_test = [
("911", "US"), ("999", "GB"), ("112", "DE"),
("411", "US"), ("118", "GB"), ("611", "US")
]
for number, region in short_numbers_to_test:
result = analyze_short_number(number, region)
if "error" not in result:
print(f"{number} ({region}): {'Emergency' if result['is_emergency'] else 'Service'} "
f"- {result['cost_description']}")Install with Tessl CLI
npx tessl i tessl/pypi-phonenumbers