title: Python: How to generate a random phone number?
body: <p>Not a duplicate of <a href="https://stackoverflow.com/questions/26226801/making-random-phone-number-xxx-xxx-xxxx">Making random phone number xxx-xxx-xxxx</a></p>
  
  <p>My project uses <a href="https://github.com/daviddrysdale/python-phonenumbers" rel="nofollow noreferrer">python-phonenumbers</a> and <a href="https://github.com/stefanfoulis/django-phonenumber-field" rel="nofollow noreferrer">django-phonenumber-field</a> for phone number validation. Within the project are vast lists of custom validation rules, for which naive approach like this will not be sufficient:</p>
  
  <pre><code>&gt;&gt;&gt; import functools
  &gt;&gt;&gt; import random
  &gt;&gt;&gt; a = functools.partial(random.randint, 0, 9)
  &gt;&gt;&gt; gen = lambda: "+{}-{}{}{}-{}{}{}-{}{}{}{}".format(a(), a(), a(), a(), a(), a(), a(), a(), a(), a(), a())
  &gt;&gt;&gt; gen()
  '+2-758-702-0180'  # Obviously wrong
  &gt;&gt;&gt; gen()
  '+1-911-555-0180'  # Obviously wrong, it has 911 in it
  </code></pre>
  
  <p>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?</p>
  
  <pre><code>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
  </code></pre>