pythonphone-number

Python: How to generate a random phone number?


Not a duplicate of Making random phone number xxx-xxx-xxxx

My project uses python-phonenumbers and django-phonenumber-field for phone number validation. Within the project are vast lists of custom validation rules, for which naive approach like this will not be sufficient:

>>> import functools
>>> import random
>>> a = functools.partial(random.randint, 0, 9)
>>> gen = lambda: "+{}-{}{}{}-{}{}{}-{}{}{}{}".format(a(), a(), a(), a(), a(), a(), a(), a(), a(), a(), a())
>>> gen()
'+2-758-702-0180'  # Obviously wrong
>>> gen()
'+1-911-555-0180'  # Obviously wrong, it has 911 in it

So, without resorting to a brute-force while loop that has no upper bound, and without introducing an upper bound for such trivial problems, what better ways are there to generate valid phone numbers accepted by the validator itself?

from phonenumber_field.validators import validate_international_phonenumber
from django.core.exceptions import ValidationError

def generate_valid_number():
    while True:  # While loops are not desired, even with an upper bound!
        try:
            number = gen()
            validate_international_phonenumber(number)
            return number
        except ValidationError:
            pass

Solution

  • I think the answer that davidn gave to this question should work especially since you're already using python-phonenumbers

    I would recommend to use the phonenumbers package which is a python port of Google's libphonenumber which includes a data set of mobile carriers now:

    import phonenumbers 
    from phonenumbers import carrier
    from phonenumbers.phonenumberutil import number_type
    
    number = "+49 176 1234 5678"
    carrier._is_mobile(number_type(phonenumbers.parse(number))) 
    

    This will return True in case number is a mobile number or False otherwise. Note that the number must be a valid international number or an exception will be thrown. You can also use phonenumbers to parse phonenumber given a region hint.