Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/phonenumbers/phonenumberutil.py: 64%

Shortcuts on this page

r m x   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

1205 statements  

1# -*- coding: utf-8 -*- 

2"""Python phone number parsing and formatting library 

3 

4If you use this library, and want to be notified about important changes, 

5please sign up to the libphonenumber mailing list at 

6https://groups.google.com/forum/#!aboutgroup/libphonenumber-discuss. 

7 

8NOTE: A lot of methods in this module require Region Code strings. These must 

9be provided using CLDR two-letter region-code format. These should be in 

10upper-case. The list of the codes can be found here: 

11http://www.iso.org/iso/country_codes/iso_3166_code_lists/country_names_and_code_elements.htm 

12""" 

13# Based on original Java code: 

14# java/src/com/google/i18n/phonenumbers/PhoneNumberUtil.java 

15# Copyright (C) 2009-2011 The Libphonenumber Authors 

16# 

17# Licensed under the Apache License, Version 2.0 (the "License"); 

18# you may not use this file except in compliance with the License. 

19# You may obtain a copy of the License at 

20# 

21# http://www.apache.org/licenses/LICENSE-2.0 

22# 

23# Unless required by applicable law or agreed to in writing, software 

24# distributed under the License is distributed on an "AS IS" BASIS, 

25# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 

26# See the License for the specific language governing permissions and 

27# limitations under the License. 

28import sys 

29import re 

30 

31from .re_util import fullmatch # Extra regexp function; see README 

32from .re_util import re_compile 

33from .util import UnicodeMixin, u, unicod, prnt, to_long 

34from .util import U_EMPTY_STRING, U_SPACE, U_DASH, U_TILDE, U_ZERO, U_SEMICOLON 

35from .unicode_util import digit as unicode_digit 

36 

37# Data class definitions 

38from .phonenumber import PhoneNumber, CountryCodeSource 

39from .phonemetadata import NumberFormat, PhoneMetadata, REGION_CODE_FOR_NON_GEO_ENTITY 

40 

41# Import auto-generated data structures 

42try: 

43 from .data import _COUNTRY_CODE_TO_REGION_CODE 

44except ImportError: # pragma no cover 

45 # Before the generated code exists, the data/ directory is empty. 

46 # The generation process imports this module, creating a circular 

47 # dependency. The hack below works around this. 

48 import os 

49 if (os.path.basename(sys.argv[0]) == "buildmetadatafromxml.py" or 

50 os.path.basename(sys.argv[0]) == "buildprefixdata.py"): 

51 prnt("Failed to import generated data (but OK as during autogeneration)", file=sys.stderr) 

52 _COUNTRY_CODE_TO_REGION_CODE = {1: ("US",)} 

53 else: 

54 raise 

55 

56# Set the master map from country code to region code. The 

57# extra level of indirection allows the unit test to replace 

58# the map with test data. 

59COUNTRY_CODE_TO_REGION_CODE = _COUNTRY_CODE_TO_REGION_CODE 

60 

61# Naming convention for phone number arguments and variables: 

62# - string arguments are named 'number' 

63# - PhoneNumber objects are named 'numobj' 

64 

65# Flags to use when compiling regular expressions for phone numbers. 

66_REGEX_FLAGS = re.UNICODE | re.IGNORECASE 

67# The minimum and maximum length of the national significant number. 

68_MIN_LENGTH_FOR_NSN = 2 

69# The ITU says the maximum length should be 15, but we have found longer 

70# numbers in Germany. 

71_MAX_LENGTH_FOR_NSN = 17 

72# The maximum length of the country calling code. 

73_MAX_LENGTH_COUNTRY_CODE = 3 

74# We don't allow input strings for parsing to be longer than 250 chars. This 

75# prevents malicious input from overflowing the regular-expression engine. 

76_MAX_INPUT_STRING_LENGTH = 250 

77# Region-code for the unknown region. 

78UNKNOWN_REGION = u("ZZ") 

79# The set of regions that share country calling code 1. 

80_NANPA_COUNTRY_CODE = 1 

81# Map of country calling codes that use a mobile token before the area 

82# code. One example of when this is relevant is when determining the length of 

83# the national destination code, which should be the length of the area code 

84# plus the length of the mobile token. 

85_MOBILE_TOKEN_MAPPINGS = {54: u('9')} 

86# Set of country codes that have geographically assigned mobile numbers (see 

87# GEO_MOBILE_COUNTRIES below) which are not based on *area codes*. For example, 

88# in China mobile numbers start with a carrier indicator, and beyond that are 

89# geographically assigned: this carrier indicator is not considered to be an 

90# area code. 

91_GEO_MOBILE_COUNTRIES_WITHOUT_MOBILE_AREA_CODES = frozenset(( 

92 86,)) # China 

93# Set of country codes that doesn't have national prefix, but it has area codes. 

94_COUNTRIES_WITHOUT_NATIONAL_PREFIX_WITH_AREA_CODES = frozenset(( 

95 52,)) # Mexico 

96 

97# Set of country calling codes that have geographically assigned mobile 

98# numbers. This may not be complete; we add calling codes case by case, as we 

99# find geographical mobile numbers or hear from user reports. Note that 

100# countries like the US, where we can't distinguish between fixed-line or 

101# mobile numbers, are not listed here, since we consider FIXED_LINE_OR_MOBILE 

102# to be a possibly geographically-related type anyway (like FIXED_LINE). 

103_GEO_MOBILE_COUNTRIES = _GEO_MOBILE_COUNTRIES_WITHOUT_MOBILE_AREA_CODES | set(( 

104 52, # Mexico 

105 54, # Argentina 

106 55, # Brazil 

107 62)) # Indonesia: some prefixes only (fixed CMDA wireless) 

108# The PLUS_SIGN signifies the international prefix. 

109_PLUS_SIGN = u("+") 

110_STAR_SIGN = u('*') 

111_RFC3966_EXTN_PREFIX = u(";ext=") 

112_RFC3966_PREFIX = u("tel:") 

113_RFC3966_PHONE_CONTEXT = u(";phone-context=") 

114_RFC3966_ISDN_SUBADDRESS = u(";isub=") 

115 

116# Simple ASCII digits map used to populate _ALPHA_PHONE_MAPPINGS and 

117# _ALL_PLUS_NUMBER_GROUPING_SYMBOLS. 

118_ASCII_DIGITS_MAP = {u("0"): u("0"), u("1"): u("1"), 

119 u("2"): u("2"), u("3"): u("3"), 

120 u("4"): u("4"), u("5"): u("5"), 

121 u("6"): u("6"), u("7"): u("7"), 

122 u("8"): u("8"), u("9"): u("9")} 

123 

124# Only upper-case variants of alpha characters are stored. 

125_ALPHA_MAPPINGS = {u("A"): u("2"), 

126 u("B"): u("2"), 

127 u("C"): u("2"), 

128 u("D"): u("3"), 

129 u("E"): u("3"), 

130 u("F"): u("3"), 

131 u("G"): u("4"), 

132 u("H"): u("4"), 

133 u("I"): u("4"), 

134 u("J"): u("5"), 

135 u("K"): u("5"), 

136 u("L"): u("5"), 

137 u("M"): u("6"), 

138 u("N"): u("6"), 

139 u("O"): u("6"), 

140 u("P"): u("7"), 

141 u("Q"): u("7"), 

142 u("R"): u("7"), 

143 u("S"): u("7"), 

144 u("T"): u("8"), 

145 u("U"): u("8"), 

146 u("V"): u("8"), 

147 u("W"): u("9"), 

148 u("X"): u("9"), 

149 u("Y"): u("9"), 

150 u("Z"): u("9"), } 

151# For performance reasons, amalgamate both into one map. 

152_ALPHA_PHONE_MAPPINGS = dict(_ALPHA_MAPPINGS, **_ASCII_DIGITS_MAP) 

153 

154# A map that contains characters that are essential when dialling. That means 

155# any of the characters in this map must not be removed from a number when 

156# dialling, otherwise the call will not reach the intended destination. 

157_DIALLABLE_CHAR_MAPPINGS = dict({_PLUS_SIGN: _PLUS_SIGN, 

158 u('*'): u('*'), 

159 u('#'): u('#')}, 

160 **_ASCII_DIGITS_MAP) 

161 

162# Separate map of all symbols that we wish to retain when formatting alpha 

163# numbers. This includes digits, ASCII letters and number grouping symbols 

164# such as "-" and " ". 

165_ALL_PLUS_NUMBER_GROUPING_SYMBOLS = dict({u("-"): u("-"), # Add grouping symbols. 

166 u("\uFF0D"): u("-"), 

167 u("\u2010"): u("-"), 

168 u("\u2011"): u("-"), 

169 u("\u2012"): u("-"), 

170 u("\u2013"): u("-"), 

171 u("\u2014"): u("-"), 

172 u("\u2015"): u("-"), 

173 u("\u2212"): u("-"), 

174 u("/"): u("/"), 

175 u("\uFF0F"): u("/"), 

176 u(" "): u(" "), 

177 u("\u3000"): u(" "), 

178 u("\u2060"): u(" "), 

179 u("."): u("."), 

180 u("\uFF0E"): u(".")}, 

181 # Put (lower letter -> upper letter) and 

182 # (upper letter -> upper letter) mappings. 

183 **dict([(_c.lower(), _c) for _c in _ALPHA_MAPPINGS.keys()] + 

184 [(_c, _c) for _c in _ALPHA_MAPPINGS.keys()], 

185 **_ASCII_DIGITS_MAP)) 

186 

187# Pattern that makes it easy to distinguish whether a region has a single international dialing 

188# prefix or not. If a region has a single international prefix (e.g. 011 in USA), it will be 

189# represented as a string that contains a sequence of ASCII digits, and possibly a tilde, which 

190# signals waiting for the tone. If there are multiple available international prefixes in a 

191# region, they will be represented as a regex string that always contains one or more characters 

192# that are not ASCII digits or a tilde. 

193_SINGLE_INTERNATIONAL_PREFIX = re.compile(u("[\\d]+(?:[~\u2053\u223C\uFF5E][\\d]+)?")) 

194 

195# Regular expression of acceptable punctuation found in phone numbers. This 

196# excludes punctuation found as a leading character only. 

197 

198# Regular expression of acceptable punctuation found in phone numbers, used to find numbers in 

199# text and to decide what is a viable phone number. This excludes diallable characters. 

200# This consists of dash characters, white space characters, full stops, slashes, square brackets, 

201# parentheses and tildes. It also includes the letter 'x' as that is found as a placeholder for 

202# carrier information in some phone numbers. Full-width variants are also present. 

203_VALID_PUNCTUATION = (u("-x\u2010-\u2015\u2212\u30FC\uFF0D-\uFF0F ") + 

204 u("\u00A0\u00AD\u200B\u2060\u3000()\uFF08\uFF09\uFF3B\uFF3D.\\[\\]/~\u2053\u223C\uFF5E")) 

205 

206_DIGITS = unicod('\\d') # Java "\\p{Nd}", so need "(?u)" or re.UNICODE wherever this is used 

207# We accept alpha characters in phone numbers, ASCII only, upper and lower 

208# case. 

209_VALID_ALPHA = (U_EMPTY_STRING.join(_ALPHA_MAPPINGS.keys()) + 

210 U_EMPTY_STRING.join([_k.lower() for _k in _ALPHA_MAPPINGS.keys()])) 

211_PLUS_CHARS = u("+\uFF0B") 

212_PLUS_CHARS_PATTERN = re.compile(u("[") + _PLUS_CHARS + u("]+")) 

213_SEPARATOR_PATTERN = re.compile(u("[") + _VALID_PUNCTUATION + u("]+")) 

214_CAPTURING_DIGIT_PATTERN = re.compile(u("(") + _DIGITS + u(")"), re.UNICODE) 

215 

216# Regular expression of acceptable characters that may start a phone number 

217# for the purposes of parsing. This allows us to strip away meaningless 

218# prefixes to phone numbers that may be mistakenly given to us. This consists 

219# of digits, the plus symbol and arabic-indic digits. This does not contain 

220# alpha characters, although they may be used later in the number. It also 

221# does not include other punctuation, as this will be stripped later during 

222# parsing and is of no information value when parsing a number. 

223_VALID_START_CHAR = u("[") + _PLUS_CHARS + _DIGITS + u("]") 

224_VALID_START_CHAR_PATTERN = re.compile(_VALID_START_CHAR, re.UNICODE) 

225 

226# Regular expression of characters typically used to start a second phone 

227# number for the purposes of parsing. This allows us to strip off parts of the 

228# number that are actually the start of another number, such as for: (530) 

229# 583-6985 x302/x2303 -> the second extension here makes this actually two 

230# phone numbers, (530) 583-6985 x302 and (530) 583-6985 x2303. We remove the 

231# second extension so that the first number is parsed correctly. 

232_SECOND_NUMBER_START = u("[\\\\/] *x") 

233_SECOND_NUMBER_START_PATTERN = re.compile(_SECOND_NUMBER_START) 

234 

235# Regular expression of trailing characters that we want to remove. We remove 

236# all characters that are not alpha or numerical characters. The hash 

237# character is retained here, as it may signify the previous block was an 

238# extension. 

239# 

240# The original Java regexp is: 

241# [[\\P{N}&&\\P{L}]&&[^#]]+$ 

242# which splits out as: 

243# [ ]+$ : >=1 of the following chars at end of string 

244# [ ]&&[ ] : intersection of these two sets of chars 

245# [ && ] : intersection of these two sets of chars 

246# \\P{N} : characters without the "Number" Unicode property 

247# \\P{L} : characters without the "Letter" Unicode property 

248# [^#] : character other than hash 

249# which nets down to: >=1 non-Number, non-Letter, non-# characters at string end 

250# In Python Unicode regexp mode '(?u)', the class '[^#\w]' will match anything 

251# that is not # and is not alphanumeric and is not underscore. 

252_UNWANTED_END_CHARS = u(r"(?u)(?:_|[^#\w])+$") 

253_UNWANTED_END_CHAR_PATTERN = re.compile(_UNWANTED_END_CHARS) 

254 

255# We use this pattern to check if the phone number has at least three letters 

256# in it - if so, then we treat it as a number where some phone-number digits 

257# are represented by letters. 

258_VALID_ALPHA_PHONE_PATTERN = re.compile(u("(?:.*?[A-Za-z]){3}.*")) 

259 

260# Regular expression of viable phone numbers. This is location 

261# independent. Checks we have at least three leading digits, and only valid 

262# punctuation, alpha characters and digits in the phone number. Does not 

263# include extension data. The symbol 'x' is allowed here as valid punctuation 

264# since it is often used as a placeholder for carrier codes, for example in 

265# Brazilian phone numbers. We also allow multiple "+" characters at the start. 

266# Corresponds to the following: 

267# [digits]{minLengthNsn}| 

268# plus_sign*(([punctuation]|[star])*[digits]){3,}([punctuation]|[star]|[digits]|[alpha])* 

269# 

270# The first reg-ex is to allow short numbers (two digits long) to be parsed if 

271# they are entered as "15" etc, but only if there is no punctuation in 

272# them. The second expression restricts the number of digits to three or more, 

273# but then allows them to be in international form, and to have 

274# alpha-characters and punctuation. 

275# 

276# Note VALID_PUNCTUATION starts with a -, so must be the first in the range. 

277_VALID_PHONE_NUMBER = (_DIGITS + (u("{%d}") % _MIN_LENGTH_FOR_NSN) + u("|") + 

278 u("[") + _PLUS_CHARS + u("]*(?:[") + _VALID_PUNCTUATION + _STAR_SIGN + u("]*") + _DIGITS + u("){3,}[") + 

279 _VALID_PUNCTUATION + _STAR_SIGN + _VALID_ALPHA + _DIGITS + u("]*")) 

280 

281# Default extension prefix to use when formatting. This will be put in front 

282# of any extension component of the number, after the main national number is 

283# formatted. For example, if you wish the default extension formatting to be 

284# " extn: 3456", then you should specify " extn: " here as the default 

285# extension prefix. This can be overridden by region-specific preferences. 

286_DEFAULT_EXTN_PREFIX = u(" ext. ") 

287 

288 

289# Helper method for constructing regular expressions for parsing. Creates an expression that 

290# captures up to max_length digits. 

291def _extn_digits(max_length): 

292 return u("(") + _DIGITS + (u("{1,%d})") % max_length) 

293 

294 

295# Helper initialiser method to create the regular-expression pattern to match extensions. 

296# Note that there are currently six capturing groups for the extension itself. If this number is 

297# changed, _maybe_strip_extension needs to be updated. 

298def _create_extn_pattern(for_parsing): 

299 # We cap the maximum length of an extension based on the ambiguity of the way the extension is 

300 # prefixed. As per ITU, the officially allowed length for extensions is actually 40, but we 

301 # don't support this since we haven't seen real examples and this introduces many false 

302 # interpretations as the extension labels are not standardized. 

303 ext_limit_after_explicit_label = 20 

304 ext_limit_after_likely_label = 15 

305 ext_limit_after_ambiguous_char = 9 

306 ext_limit_when_not_sure = 6 

307 

308 possible_separators_between_number_and_ext_label = u("[ \u00A0\\t,]*") 

309 # Optional full stop (.) or colon, followed by zero or more spaces/tabs/commas. 

310 possible_chars_after_ext_label = u("[:\\.\uFF0E]?[ \u00A0\\t,-]*") 

311 optional_extn_suffix = u("#?") 

312 

313 # Here the extension is called out in more explicit way, i.e mentioning it obvious patterns 

314 # like "ext.". Canonical-equivalence doesn't seem to be an option with Android java, so we 

315 # allow two options for representing the accented o - the character itself, and one in the 

316 # unicode decomposed form with the combining acute accent. 

317 explicit_ext_labels = u("(?:e?xt(?:ensi(?:o\u0301?|\u00F3))?n?|\uFF45?\uFF58\uFF54\uFF4E?|\u0434\u043E\u0431|anexo)") 

318 # One-character symbols that can be used to indicate an extension, and less commonly used 

319 # or more ambiguous extension labels. 

320 ambiguous_ext_labels = u("(?:[x\uFF58#\uFF03~\uFF5E]|int|\uFF49\uFF4E\uFF54)") 

321 # When extension is not separated clearly. 

322 ambiguous_separator = u("[- ]+") 

323 

324 rfc_extn = _RFC3966_EXTN_PREFIX + _extn_digits(ext_limit_after_explicit_label) 

325 explicit_extn = (possible_separators_between_number_and_ext_label + explicit_ext_labels + 

326 possible_chars_after_ext_label + _extn_digits(ext_limit_after_explicit_label) + 

327 optional_extn_suffix) 

328 ambiguous_extn = (possible_separators_between_number_and_ext_label + ambiguous_ext_labels + 

329 possible_chars_after_ext_label + _extn_digits(ext_limit_after_ambiguous_char) + optional_extn_suffix) 

330 american_style_extn_with_suffix = (ambiguous_separator + _extn_digits(ext_limit_when_not_sure) + u("#")) 

331 

332 # The first regular expression covers RFC 3966 format, where the extension is added using 

333 # ";ext=". The second more generic where extension is mentioned with explicit labels like 

334 # "ext:". In both the above cases we allow more numbers in extension than any other extension 

335 # labels. The third one captures when single character extension labels or less commonly used 

336 # labels are used. In such cases we capture fewer extension digits in order to reduce the 

337 # chance of falsely interpreting two numbers beside each other as a number + extension. The 

338 # fourth one covers the special case of American numbers where the extension is written with a 

339 # hash at the end, such as "- 503#". 

340 extension_pattern = (rfc_extn + u("|") + 

341 explicit_extn + u("|") + 

342 ambiguous_extn + u("|") + 

343 american_style_extn_with_suffix) 

344 # Additional pattern that is supported when parsing extensions, not when matching. 

345 if for_parsing: 

346 # This is same as possible_separators_between_number_and_ext_label, but not matching comma as 

347 # extension label may have it. 

348 possible_separators_number_ext_label_no_comma = u("[ \u00A0\\t]*") 

349 # ",," is commonly used for auto dialling the extension when connected. First comma is matched 

350 # through possible_separators_between_number_and_ext_label, so we do not repeat it here. Semi-colon 

351 # works in Iphone and Android also to pop up a button with the extension number following. 

352 auto_dialling_and_ext_labels_found = u("(?:,{2}|;)") 

353 

354 auto_dialling_extn = (possible_separators_number_ext_label_no_comma + 

355 auto_dialling_and_ext_labels_found + possible_chars_after_ext_label + 

356 _extn_digits(ext_limit_after_likely_label) + optional_extn_suffix) 

357 only_commas_extn = (possible_separators_number_ext_label_no_comma + 

358 u("(?:,)+") + possible_chars_after_ext_label + _extn_digits(ext_limit_after_ambiguous_char) + 

359 optional_extn_suffix) 

360 # Here the first pattern is exclusively for extension autodialling formats which are used 

361 # when dialling and in this case we accept longer extensions. However, the second pattern 

362 # is more liberal on the number of commas that acts as extension labels, so we have a strict 

363 # cap on the number of digits in such extensions. 

364 return (extension_pattern + u("|") + 

365 auto_dialling_extn + u("|") + 

366 only_commas_extn) 

367 return extension_pattern 

368 

369 

370# Regexp of all possible ways to write extensions, for use when parsing. This 

371# will be run as a case-insensitive regexp match. Wide character versions are 

372# also provided after each ASCII version. 

373_EXTN_PATTERNS_FOR_PARSING = _create_extn_pattern(True) 

374_EXTN_PATTERNS_FOR_MATCHING = _create_extn_pattern(False) 

375 

376# Regular expression of valid global-number-digits for the phone-context 

377# parameter, following the syntax defined in RFC3966. 

378_RFC3966_VISUAL_SEPARATOR = "[\\-\\.\\(\\)]?" 

379_RFC3966_PHONE_DIGIT = "(" + _DIGITS + "|" + _RFC3966_VISUAL_SEPARATOR + ")" 

380_RFC3966_GLOBAL_NUMBER_DIGITS = "^\\" + _PLUS_SIGN + _RFC3966_PHONE_DIGIT + "*" + _DIGITS + _RFC3966_PHONE_DIGIT + "*$" 

381_RFC3966_GLOBAL_NUMBER_DIGITS_PATTERN = re.compile(_RFC3966_GLOBAL_NUMBER_DIGITS) 

382 

383# Regular expression of valid domainname for the phone-context parameter, 

384# following the syntax defined in RFC3966. 

385_ALPHANUM = _VALID_ALPHA + _DIGITS 

386_RFC3966_DOMAINLABEL = "[" + _ALPHANUM + "]+((\\-)*[" + _ALPHANUM + "])*" 

387_RFC3966_TOPLABEL = "[" + _VALID_ALPHA + "]+((\\-)*[" + _ALPHANUM + "])*" 

388_RFC3966_DOMAINNAME = "^(" + _RFC3966_DOMAINLABEL + "\\.)*" + _RFC3966_TOPLABEL + "\\.?$" 

389_RFC3966_DOMAINNAME_PATTERN = re.compile(_RFC3966_DOMAINNAME) 

390 

391# Regexp of all known extension prefixes used by different regions followed by 

392# 1 or more valid digits, for use when parsing. 

393_EXTN_PATTERN = re.compile(u("(?:") + _EXTN_PATTERNS_FOR_PARSING + u(")$"), _REGEX_FLAGS) 

394 

395# We append optionally the extension pattern to the end here, as a valid phone 

396# number may have an extension prefix appended, followed by 1 or more digits. 

397_VALID_PHONE_NUMBER_PATTERN = re.compile(_VALID_PHONE_NUMBER + u("(?:") + _EXTN_PATTERNS_FOR_PARSING + u(")?"), _REGEX_FLAGS) 

398 

399# We use a non-capturing group because Python's re.split() returns any capturing 

400# groups interspersed with the other results (unlike Java's Pattern.split()). 

401NON_DIGITS_PATTERN = re.compile(u("(?:\\D+)")) 

402 

403# The FIRST_GROUP_PATTERN was originally set to \1 but there are some 

404# countries for which the first group is not used in the national pattern 

405# (e.g. Argentina) so the \1 group does not match correctly. Therefore, we 

406# use \d, so that the first group actually used in the pattern will be 

407# matched. 

408_FIRST_GROUP_PATTERN = re.compile(u(r"(\\\d)")) 

409# Constants used in the formatting rules to represent the national prefix, first group and 

410# carrier code respectively. 

411_NP_STRING = "$NP" 

412_FG_STRING = "$FG" 

413_CC_STRING = "$CC" 

414 

415# A pattern that is used to determine if the national prefix formatting rule 

416# has the first group only, i.e., does not start with the national 

417# prefix. Note that the pattern explicitly allows for unbalanced parentheses. 

418_FIRST_GROUP_ONLY_PREFIX_PATTERN = re.compile("\\(?\\\\1\\)?") 

419 

420 

421class PhoneNumberFormat(object): 

422 """ 

423 Phone number format. 

424 

425 INTERNATIONAL and NATIONAL formats are consistent with the definition in 

426 ITU-T Recommendation E123. However we follow local conventions such as using 

427 '-' instead of whitespace as separators. For example, the number of the 

428 Google Switzerland office will be written as "+41 44 668 1800" in 

429 INTERNATIONAL format, and as "044 668 1800" in NATIONAL format. E164 format 

430 is as per INTERNATIONAL format but with no formatting applied, 

431 e.g. "+41446681800". RFC3966 is as per INTERNATIONAL format, but with all 

432 spaces and other separating symbols replaced with a hyphen, and with any 

433 phone number extension appended with ";ext=". It also will have a prefix of 

434 "tel:" added, e.g. "tel:+41-44-668-1800". 

435 

436 Note: If you are considering storing the number in a neutral format, you 

437 are highly advised to use the PhoneNumber class. 

438 """ 

439 E164 = 0 

440 INTERNATIONAL = 1 

441 NATIONAL = 2 

442 RFC3966 = 3 

443 

444 @classmethod 

445 def to_string(cls, val): 

446 """Return a string representation of a PhoneNumberFormat value""" 

447 if val == PhoneNumberFormat.E164: 

448 return u("E164") 

449 elif val == PhoneNumberFormat.INTERNATIONAL: 

450 return u("INTERNATIONAL") 

451 elif val == PhoneNumberFormat.NATIONAL: 

452 return u("NATIONAL") 

453 elif val == PhoneNumberFormat.RFC3966: 

454 return u("RFC3966") 

455 else: 

456 return u("INVALID (%d)" % val) 

457 

458 

459class PhoneNumberType(object): 

460 """Type of phone numbers.""" 

461 FIXED_LINE = 0 

462 MOBILE = 1 

463 # In some regions (e.g. the USA), it is impossible to distinguish between 

464 # fixed-line and mobile numbers by looking at the phone number itself. 

465 FIXED_LINE_OR_MOBILE = 2 

466 # Freephone lines 

467 TOLL_FREE = 3 

468 PREMIUM_RATE = 4 

469 # The cost of this call is shared between the caller and the recipient, 

470 # and is hence typically less than PREMIUM_RATE calls. See 

471 # http://en.wikipedia.org/wiki/Shared_Cost_Service for more information. 

472 SHARED_COST = 5 

473 # Voice over IP numbers. This includes TSoIP (Telephony Service over IP). 

474 VOIP = 6 

475 # A personal number is associated with a particular person, and may be 

476 # routed to either a MOBILE or FIXED_LINE number. Some more information 

477 # can be found here: http://en.wikipedia.org/wiki/Personal_Numbers 

478 PERSONAL_NUMBER = 7 

479 PAGER = 8 

480 # Used for "Universal Access Numbers" or "Company Numbers". They may be 

481 # further routed to specific offices, but allow one number to be used for 

482 # a company. 

483 UAN = 9 

484 # Used for "Voice Mail Access Numbers". 

485 VOICEMAIL = 10 

486 # A phone number is of type UNKNOWN when it does not fit any of the known 

487 # patterns for a specific region. 

488 UNKNOWN = 99 

489 

490 @classmethod 

491 def values(cls): 

492 return (PhoneNumberType.FIXED_LINE, 

493 PhoneNumberType.MOBILE, 

494 PhoneNumberType.FIXED_LINE_OR_MOBILE, 

495 PhoneNumberType.TOLL_FREE, 

496 PhoneNumberType.PREMIUM_RATE, 

497 PhoneNumberType.SHARED_COST, 

498 PhoneNumberType.VOIP, 

499 PhoneNumberType.PERSONAL_NUMBER, 

500 PhoneNumberType.PAGER, 

501 PhoneNumberType.UAN, 

502 PhoneNumberType.VOICEMAIL, 

503 PhoneNumberType.UNKNOWN) 

504 

505 @classmethod 

506 def to_string(cls, val): 

507 """Return a string representation of a PhoneNumberType value""" 

508 if val == PhoneNumberType.FIXED_LINE: 

509 return u("FIXED_LINE") 

510 elif val == PhoneNumberType.MOBILE: 

511 return u("MOBILE") 

512 elif val == PhoneNumberType.FIXED_LINE_OR_MOBILE: 

513 return u("FIXED_LINE_OR_MOBILE") 

514 elif val == PhoneNumberType.TOLL_FREE: 

515 return u("TOLL_FREE") 

516 elif val == PhoneNumberType.PREMIUM_RATE: 

517 return u("PREMIUM_RATE") 

518 elif val == PhoneNumberType.SHARED_COST: 

519 return u("SHARED_COST") 

520 elif val == PhoneNumberType.VOIP: 

521 return u("VOIP") 

522 elif val == PhoneNumberType.PERSONAL_NUMBER: 

523 return u("PERSONAL_NUMBER") 

524 elif val == PhoneNumberType.PAGER: 

525 return u("PAGER") 

526 elif val == PhoneNumberType.UAN: 

527 return u("UAN") 

528 elif val == PhoneNumberType.VOICEMAIL: 

529 return u("VOICEMAIL") 

530 elif val == PhoneNumberType.UNKNOWN: 

531 return u("UNKNOWN") 

532 else: 

533 return u("INVALID (%d)" % val) 

534 

535 

536class MatchType(object): 

537 """Types of phone number matches.""" 

538 # Not a telephone number 

539 NOT_A_NUMBER = 0 

540 # None of the match types below apply 

541 NO_MATCH = 1 

542 # Returns SHORT_NSN_MATCH if either or both has no region specified, or 

543 # the region specified is the same, and one NSN could be a shorter version 

544 # of the other number. This includes the case where one has an extension 

545 # specified, and the other does not. 

546 SHORT_NSN_MATCH = 2 

547 # Either or both has no region specified, and the NSNs and extensions are 

548 # the same. 

549 NSN_MATCH = 3 

550 # The country_code, NSN, presence of a leading zero for Italian numbers 

551 # and any extension present are the same. 

552 EXACT_MATCH = 4 

553 

554 @classmethod 

555 def to_string(cls, val): 

556 """Return a string representation of a MatchType value""" 

557 if val == MatchType.NOT_A_NUMBER: 

558 return u("NOT_A_NUMBER") 

559 elif val == MatchType.NO_MATCH: 

560 return u("NO_MATCH") 

561 elif val == MatchType.SHORT_NSN_MATCH: 

562 return u("SHORT_NSN_MATCH") 

563 elif val == MatchType.NSN_MATCH: 

564 return u("NSN_MATCH") 

565 elif val == MatchType.EXACT_MATCH: 

566 return u("EXACT_MATCH") 

567 else: 

568 return u("INVALID (%d)" % val) 

569 

570 

571class ValidationResult(object): 

572 """Possible outcomes when testing if a PhoneNumber is a possible number.""" 

573 # The number length matches that of valid numbers for this region. 

574 IS_POSSIBLE = 0 

575 # The number length matches that of local numbers for this region only 

576 # (i.e. numbers that may be able to be dialled within an area, but do not 

577 # have all the information to be dialled from anywhere inside or outside 

578 # the country). 

579 IS_POSSIBLE_LOCAL_ONLY = 4 

580 # The number has an invalid country calling code. 

581 INVALID_COUNTRY_CODE = 1 

582 # The number is shorter than all valid numbers for this region. 

583 TOO_SHORT = 2 

584 # The number is longer than the shortest valid numbers for this region, 

585 # shorter than the longest valid numbers for this region, and does not 

586 # itself have a number length that matches valid numbers for this region. 

587 # This can also be returned in the case where 

588 # is_possible_number_for_type_with_reason was called, and there are no 

589 # numbers of this type at all for this region. 

590 INVALID_LENGTH = 5 

591 # The number is longer than all valid numbers for this region. 

592 TOO_LONG = 3 

593 

594 @classmethod 

595 def to_string(cls, val): 

596 """Return a string representation of a ValidationResult value""" 

597 if val == ValidationResult.IS_POSSIBLE: 

598 return u("IS_POSSIBLE") 

599 elif val == ValidationResult.IS_POSSIBLE_LOCAL_ONLY: 

600 return u("IS_POSSIBLE_LOCAL_ONLY") 

601 elif val == ValidationResult.INVALID_COUNTRY_CODE: 

602 return u("INVALID_COUNTRY_CODE") 

603 elif val == ValidationResult.TOO_SHORT: 

604 return u("TOO_SHORT") 

605 elif val == ValidationResult.INVALID_LENGTH: 

606 return u("INVALID_LENGTH") 

607 elif val == ValidationResult.TOO_LONG: 

608 return u("TOO_LONG") 

609 else: 

610 return u("INVALID (%d)" % val) 

611 

612 

613# Derived data structures 

614SUPPORTED_REGIONS = set() 

615COUNTRY_CODES_FOR_NON_GEO_REGIONS = set() 

616_NANPA_REGIONS = set() 

617 

618 

619def _regenerate_derived_data(): 

620 global SUPPORTED_REGIONS, COUNTRY_CODES_FOR_NON_GEO_REGIONS, _NANPA_REGIONS 

621 SUPPORTED_REGIONS.clear() 

622 COUNTRY_CODES_FOR_NON_GEO_REGIONS.clear() 

623 for cc, region_codes in COUNTRY_CODE_TO_REGION_CODE.items(): 

624 if (len(region_codes) == 1 and region_codes[0] == REGION_CODE_FOR_NON_GEO_ENTITY): 

625 COUNTRY_CODES_FOR_NON_GEO_REGIONS.add(cc) 

626 else: 

627 SUPPORTED_REGIONS.update(region_codes) 

628 if REGION_CODE_FOR_NON_GEO_ENTITY in SUPPORTED_REGIONS: # pragma no cover 

629 SUPPORTED_REGIONS.remove(REGION_CODE_FOR_NON_GEO_ENTITY) 

630 _NANPA_REGIONS.clear() 

631 _NANPA_REGIONS.update(COUNTRY_CODE_TO_REGION_CODE[_NANPA_COUNTRY_CODE]) 

632 

633 

634_regenerate_derived_data() 

635 

636 

637def _copy_number_format(other): 

638 """Return a mutable copy of the given NumberFormat object""" 

639 copy = NumberFormat(pattern=other.pattern, 

640 format=other.format, 

641 leading_digits_pattern=list(other.leading_digits_pattern), 

642 national_prefix_formatting_rule=other.national_prefix_formatting_rule, 

643 national_prefix_optional_when_formatting=other.national_prefix_optional_when_formatting, 

644 domestic_carrier_code_formatting_rule=other.domestic_carrier_code_formatting_rule) 

645 copy._mutable = True 

646 return copy 

647 

648 

649def _extract_possible_number(number): 

650 """Attempt to extract a possible number from the string passed in. 

651 

652 This currently strips all leading characters that cannot be used to 

653 start a phone number. Characters that can be used to start a phone number 

654 are defined in the VALID_START_CHAR_PATTERN. If none of these characters 

655 are found in the number passed in, an empty string is returned. This 

656 function also attempts to strip off any alternative extensions or endings 

657 if two or more are present, such as in the case of: (530) 583-6985 

658 x302/x2303. The second extension here makes this actually two phone 

659 numbers, (530) 583-6985 x302 and (530) 583-6985 x2303. We remove the 

660 second extension so that the first number is parsed correctly. 

661 

662 Arguments: 

663 number -- The string that might contain a phone number. 

664 

665 Returns the number, stripped of any non-phone-number prefix (such 

666 as "Tel:") or an empty string if no character used to start phone 

667 numbers (such as + or any digit) is found in the number 

668 """ 

669 match = _VALID_START_CHAR_PATTERN.search(number) 

670 if match: 

671 number = number[match.start():] 

672 # Remove trailing non-alpha non-numerical characters. 

673 trailing_chars_match = _UNWANTED_END_CHAR_PATTERN.search(number) 

674 if trailing_chars_match: 

675 number = number[:trailing_chars_match.start()] 

676 # Check for extra numbers at the end. 

677 second_number_match = _SECOND_NUMBER_START_PATTERN.search(number) 

678 if second_number_match: 

679 number = number[:second_number_match.start()] 

680 return number 

681 else: 

682 return U_EMPTY_STRING 

683 

684 

685def _is_viable_phone_number(number): 

686 """Checks to see if a string could possibly be a phone number. 

687 

688 At the moment, checks to see that the string begins with at least 2 

689 digits, ignoring any punctuation commonly found in phone numbers. This 

690 method does not require the number to be normalized in advance - but does 

691 assume that leading non-number symbols have been removed, such as by the 

692 method _extract_possible_number. 

693 

694 Arguments: 

695 number -- string to be checked for viability as a phone number 

696 

697 Returns True if the number could be a phone number of some sort, otherwise 

698 False 

699 """ 

700 if len(number) < _MIN_LENGTH_FOR_NSN: 

701 return False 

702 match = fullmatch(_VALID_PHONE_NUMBER_PATTERN, number) 

703 return bool(match) 

704 

705 

706def _normalize(number): 

707 """Normalizes a string of characters representing a phone number. 

708 

709 This performs the following conversions: 

710 - Punctuation is stripped. 

711 - For ALPHA/VANITY numbers: 

712 - Letters are converted to their numeric representation on a telephone 

713 keypad. The keypad used here is the one defined in ITU 

714 Recommendation E.161. This is only done if there are 3 or more 

715 letters in the number, to lessen the risk that such letters are 

716 typos. 

717 - For other numbers: 

718 - Wide-ascii digits are converted to normal ASCII (European) digits. 

719 - Arabic-Indic numerals are converted to European numerals. 

720 - Spurious alpha characters are stripped. 

721 

722 Arguments: 

723 number -- string representing a phone number 

724 

725 Returns the normalized string version of the phone number. 

726 """ 

727 m = fullmatch(_VALID_ALPHA_PHONE_PATTERN, number) 

728 if m: 

729 return _normalize_helper(number, _ALPHA_PHONE_MAPPINGS, True) 

730 else: 

731 return normalize_digits_only(number) 

732 

733 

734def normalize_digits_only(number, keep_non_digits=False): 

735 """Normalizes a string of characters representing a phone number. 

736 

737 This converts wide-ascii and arabic-indic numerals to European numerals, 

738 and strips punctuation and alpha characters (optional). 

739 

740 Arguments: 

741 number -- a string representing a phone number 

742 keep_non_digits -- whether to keep non-digits 

743 

744 Returns the normalized string version of the phone number. 

745 """ 

746 number = unicod(number) 

747 number_length = len(number) 

748 normalized_digits = U_EMPTY_STRING 

749 for ii in range(number_length): 

750 d = unicode_digit(number[ii], -1) 

751 if d != -1: 

752 normalized_digits += unicod(d) 

753 elif keep_non_digits: 

754 normalized_digits += number[ii] 

755 return normalized_digits 

756 

757 

758def normalize_diallable_chars_only(number): 

759 """Normalizes a string of characters representing a phone number. 

760 

761 This strips all characters which are not diallable on a mobile phone 

762 keypad (including all non-ASCII digits). 

763 

764 Arguments: 

765 number -- a string of characters representing a phone number 

766 

767 Returns the normalized string version of the phone number. 

768 """ 

769 return _normalize_helper(number, _DIALLABLE_CHAR_MAPPINGS, True) 

770 

771 

772def convert_alpha_characters_in_number(number): 

773 """Convert alpha chars in a number to their respective digits on a keypad, 

774 but retains existing formatting.""" 

775 return _normalize_helper(number, _ALPHA_PHONE_MAPPINGS, False) 

776 

777 

778def length_of_geographical_area_code(numobj): 

779 """Return length of the geographical area code for a number. 

780 

781 Gets the length of the geographical area code from the PhoneNumber object 

782 passed in, so that clients could use it to split a national significant 

783 number into geographical area code and subscriber number. It works in such 

784 a way that the resultant subscriber number should be diallable, at least 

785 on some devices. An example of how this could be used: 

786 

787 >>> import phonenumbers 

788 >>> numobj = phonenumbers.parse("16502530000", "US") 

789 >>> nsn = phonenumbers.national_significant_number(numobj) 

790 >>> ac_len = phonenumbers.length_of_geographical_area_code(numobj) 

791 >>> if ac_len > 0: 

792 ... area_code = nsn[:ac_len] 

793 ... subscriber_number = nsn[ac_len:] 

794 ... else: 

795 ... area_code = "" 

796 ... subscriber_number = nsn 

797 

798 N.B.: area code is a very ambiguous concept, so the I18N team generally 

799 recommends against using it for most purposes, but recommends using the 

800 more general national_number instead. Read the following carefully before 

801 deciding to use this method: 

802 

803 - geographical area codes change over time, and this method honors those 

804 changes; therefore, it doesn't guarantee the stability of the result it 

805 produces. 

806 - subscriber numbers may not be diallable from all devices (notably 

807 mobile devices, which typically require the full national_number to be 

808 dialled in most countries). 

809 - most non-geographical numbers have no area codes, including numbers 

810 from non-geographical entities. 

811 - some geographical numbers have no area codes. 

812 

813 Arguments: 

814 numobj -- The PhoneNumber object to find the length of the area code form. 

815 

816 Returns the length of area code of the PhoneNumber object passed in. 

817 """ 

818 metadata = PhoneMetadata.metadata_for_region(region_code_for_number(numobj), None) 

819 if metadata is None: 

820 return 0 

821 

822 ntype = number_type(numobj) 

823 country_code = numobj.country_code 

824 # If a country doesn't use a national prefix, and this number doesn't have 

825 # an Italian leading zero, we assume it is a closed dialling plan with no 

826 # area codes. 

827 # Note:this is our general assumption, but there are exceptions which are tracked in 

828 # _COUNTRIES_WITHOUT_NATIONAL_PREFIX_WITH_AREA_CODES. 

829 if (metadata.national_prefix is None and not numobj.italian_leading_zero and 

830 country_code not in _COUNTRIES_WITHOUT_NATIONAL_PREFIX_WITH_AREA_CODES): 

831 return 0 

832 

833 if (ntype == PhoneNumberType.MOBILE and 

834 (country_code in _GEO_MOBILE_COUNTRIES_WITHOUT_MOBILE_AREA_CODES)): 

835 # Note this is a rough heuristic; it doesn't cover Indonesia well, for 

836 # example, where area codes are present for some mobile phones but not 

837 # for others. We have no better way of representing this in the 

838 # metadata at this point. 

839 return 0 

840 

841 if not is_number_type_geographical(ntype, country_code): 

842 return 0 

843 

844 return length_of_national_destination_code(numobj) 

845 

846 

847def length_of_national_destination_code(numobj): 

848 """Return length of the national destination code code for a number. 

849 

850 Gets the length of the national destination code (NDC) from the 

851 PhoneNumber object passed in, so that clients could use it to split a 

852 national significant number into NDC and subscriber number. The NDC of a 

853 phone number is normally the first group of digit(s) right after the 

854 country calling code when the number is formatted in the international 

855 format, if there is a subscriber number part that follows. 

856 

857 N.B.: similar to an area code, not all numbers have an NDC! 

858 

859 An example of how this could be used: 

860 

861 >>> import phonenumbers 

862 >>> numobj = phonenumbers.parse("18002530000", "US") 

863 >>> nsn = phonenumbers.national_significant_number(numobj) 

864 >>> ndc_len = phonenumbers.length_of_national_destination_code(numobj) 

865 >>> if ndc_len > 0: 

866 ... national_destination_code = nsn[:ndc_len] 

867 ... subscriber_number = nsn[ndc_len:] 

868 ... else: 

869 ... national_destination_code = "" 

870 ... subscriber_number = nsn 

871 

872 Refer to the unittests to see the difference between this function and 

873 length_of_geographical_area_code. 

874 

875 Arguments: 

876 numobj -- The PhoneNumber object to find the length of the NDC from. 

877 

878 Returns the length of NDC of the PhoneNumber object passed in, which 

879 could be zero. 

880 """ 

881 if numobj.extension is not None: 

882 # We don't want to alter the object given to us, but we don't want to 

883 # include the extension when we format it, so we copy it and clear the 

884 # extension here. 

885 copied_numobj = PhoneNumber() 

886 copied_numobj.merge_from(numobj) 

887 copied_numobj.extension = None 

888 else: 

889 copied_numobj = numobj 

890 

891 nsn = format_number(copied_numobj, PhoneNumberFormat.INTERNATIONAL) 

892 number_groups = re.split(NON_DIGITS_PATTERN, nsn) 

893 

894 # The pattern will start with "+COUNTRY_CODE " so the first group will 

895 # always be the empty string (before the + symbol) and the second group 

896 # will be the country calling code. The third group will be area code if 

897 # it is not the last group. 

898 if len(number_groups) <= 3: 

899 return 0 

900 

901 if number_type(numobj) == PhoneNumberType.MOBILE: 

902 # For example Argentinian mobile numbers, when formatted in the 

903 # international format, are in the form of +54 9 NDC XXXX... As a 

904 # result, we take the length of the third group (NDC) and add the 

905 # length of the second group (which is the mobile token), which also 

906 # forms part of the national significant number. This assumes that 

907 # the mobile token is always formatted separately from the rest of the 

908 # phone number. 

909 mobile_token = country_mobile_token(numobj.country_code) 

910 if mobile_token != U_EMPTY_STRING: 

911 return len(number_groups[2]) + len(number_groups[3]) 

912 return len(number_groups[2]) 

913 

914 

915def country_mobile_token(country_code): 

916 """Returns the mobile token for the provided country calling code if it has one, otherwise 

917 returns an empty string. A mobile token is a number inserted before the area code when dialing 

918 a mobile number from that country from abroad. 

919 

920 Arguments: 

921 country_code -- the country calling code for which we want the mobile token 

922 Returns the mobile token, as a string, for the given country calling code. 

923 """ 

924 return _MOBILE_TOKEN_MAPPINGS.get(country_code, U_EMPTY_STRING) 

925 

926 

927def _normalize_helper(number, replacements, remove_non_matches): 

928 """Normalizes a string of characters representing a phone number by 

929 replacing all characters found in the accompanying map with the values 

930 therein, and stripping all other characters if remove_non_matches is true. 

931 

932 Arguments: 

933 number -- a string representing a phone number 

934 replacements -- a mapping of characters to what they should be replaced 

935 by in the normalized version of the phone number 

936 remove_non_matches -- indicates whether characters that are not able to be 

937 replaced should be stripped from the number. If this is False, 

938 they will be left unchanged in the number. 

939 

940 Returns the normalized string version of the phone number. 

941 """ 

942 normalized_number = [] 

943 for char in number: 

944 new_digit = replacements.get(char.upper(), None) 

945 if new_digit is not None: 

946 normalized_number.append(new_digit) 

947 elif not remove_non_matches: 

948 normalized_number.append(char) 

949 # If neither of the above are true, we remove this character 

950 return U_EMPTY_STRING.join(normalized_number) 

951 

952 

953def supported_calling_codes(): 

954 """Returns all country calling codes the library has metadata for, covering 

955 both non-geographical entities (global network calling codes) and those 

956 used for geographical entities. This could be used to populate a drop-down 

957 box of country calling codes for a phone-number widget, for instance. 

958 

959 Returns an unordered set of the country calling codes for every geographica 

960 and non-geographical entity the library supports. 

961 """ 

962 return set(COUNTRY_CODE_TO_REGION_CODE.keys()) 

963 

964 

965def _desc_has_possible_number_data(desc): 

966 

967 """Returns true if there is any possible number data set for a particular PhoneNumberDesc.""" 

968 # If this is empty, it means numbers of this type inherit from the "general desc" -> the value 

969 # "-1" means that no numbers exist for this type. 

970 if desc is None: 

971 return False 

972 return len(desc.possible_length) != 1 or desc.possible_length[0] != -1 

973 

974 

975# Note: desc_has_data must account for any of MetadataFilter's excludableChildFields potentially 

976# being absent from the metadata. It must check them all. For any changes in descHasData, ensure 

977# that all the excludableChildFields are still being checked. If your change is safe simply 

978# mention why during a review without needing to change MetadataFilter. 

979def _desc_has_data(desc): 

980 """Returns true if there is any data set for a particular PhoneNumberDesc.""" 

981 if desc is None: 

982 return False 

983 # Checking most properties since we don't know what's present, since a custom build may have 

984 # stripped just one of them (e.g. liteBuild strips exampleNumber). We don't bother checking the 

985 # possibleLengthsLocalOnly, since if this is the only thing that's present we don't really 

986 # support the type at all: no type-specific methods will work with only this data. 

987 return ((desc.example_number is not None) or 

988 _desc_has_possible_number_data(desc) or 

989 (desc.national_number_pattern is not None)) 

990 

991 

992def _supported_types_for_metadata(metadata): 

993 """Returns the types we have metadata for based on the PhoneMetadata object passed in, which must be non-None.""" 

994 numtypes = set() 

995 for numtype in PhoneNumberType.values(): 

996 if numtype in (PhoneNumberType.FIXED_LINE_OR_MOBILE, PhoneNumberType.UNKNOWN): 

997 # Never return FIXED_LINE_OR_MOBILE (it is a convenience type, and represents that a 

998 # particular number type can't be determined) or UNKNOWN (the non-type). 

999 continue 

1000 if _desc_has_data(_number_desc_by_type(metadata, numtype)): 

1001 numtypes.add(numtype) 

1002 return numtypes 

1003 

1004 

1005def supported_types_for_region(region_code): 

1006 """Returns the types for a given region which the library has metadata for. 

1007 

1008 Will not include FIXED_LINE_OR_MOBILE (if numbers in this region could 

1009 be classified as FIXED_LINE_OR_MOBILE, both FIXED_LINE and MOBILE would 

1010 be present) and UNKNOWN. 

1011 

1012 No types will be returned for invalid or unknown region codes. 

1013 """ 

1014 if not _is_valid_region_code(region_code): 

1015 return set() 

1016 metadata = PhoneMetadata.metadata_for_region(region_code.upper()) 

1017 assert metadata is not None # due to _is_valid_region_code() check 

1018 return _supported_types_for_metadata(metadata) 

1019 

1020 

1021def supported_types_for_non_geo_entity(country_code): 

1022 """Returns the types for a country-code belonging to a non-geographical entity 

1023 which the library has metadata for. Will not include FIXED_LINE_OR_MOBILE 

1024 (if numbers for this non-geographical entity could be classified as 

1025 FIXED_LINE_OR_MOBILE, both FIXED_LINE and MOBILE would be present) and 

1026 UNKNOWN. 

1027 

1028 No types will be returned for country calling codes that do not map to a 

1029 known non-geographical entity. 

1030 """ 

1031 metadata = PhoneMetadata.metadata_for_nongeo_region(country_code, None) 

1032 if metadata is None: 

1033 return set() 

1034 return _supported_types_for_metadata(metadata) 

1035 

1036 

1037def _formatting_rule_has_first_group_only(national_prefix_formatting_rule): 

1038 """Helper function to check if the national prefix formatting rule has the 

1039 first group only, i.e., does not start with the national prefix. 

1040 """ 

1041 if national_prefix_formatting_rule is None: 

1042 return True 

1043 return bool(fullmatch(_FIRST_GROUP_ONLY_PREFIX_PATTERN, 

1044 national_prefix_formatting_rule)) 

1045 

1046 

1047def is_number_geographical(numobj): 

1048 """Tests whether a phone number has a geographical association. 

1049 

1050 It checks if the number is associated with a certain region in the country 

1051 to which it belongs. Note that this doesn't verify if the number is 

1052 actually in use. 

1053 country_code -- the country calling code for which we want the mobile token 

1054 """ 

1055 return is_number_type_geographical(number_type(numobj), numobj.country_code) 

1056 

1057 

1058def is_number_type_geographical(num_type, country_code): 

1059 """Tests whether a phone number has a geographical association, 

1060 as represented by its type and the country it belongs to. 

1061 

1062 This version of isNumberGeographical exists since calculating the phone 

1063 number type is expensive; if we have already done this, we don't want to 

1064 do it again. 

1065 """ 

1066 return (num_type == PhoneNumberType.FIXED_LINE or 

1067 num_type == PhoneNumberType.FIXED_LINE_OR_MOBILE or 

1068 ((country_code in _GEO_MOBILE_COUNTRIES) and 

1069 num_type == PhoneNumberType.MOBILE)) 

1070 

1071 

1072def _is_valid_region_code(region_code): 

1073 """Helper function to check region code is not unknown or None""" 

1074 if region_code is None: 

1075 return False 

1076 return (region_code in SUPPORTED_REGIONS) 

1077 

1078 

1079def _has_valid_country_calling_code(country_calling_code): 

1080 return (country_calling_code in COUNTRY_CODE_TO_REGION_CODE) 

1081 

1082 

1083def format_number(numobj, num_format): 

1084 """Formats a phone number in the specified format using default rules. 

1085 

1086 Note that this does not promise to produce a phone number that the user 

1087 can dial from where they are - although we do format in either 'national' 

1088 or 'international' format depending on what the client asks for, we do not 

1089 currently support a more abbreviated format, such as for users in the same 

1090 "area" who could potentially dial the number without area code. Note that 

1091 if the phone number has a country calling code of 0 or an otherwise 

1092 invalid country calling code, we cannot work out which formatting rules to 

1093 apply so we return the national significant number with no formatting 

1094 applied. 

1095 

1096 Arguments: 

1097 numobj -- The phone number to be formatted. 

1098 num_format -- The format the phone number should be formatted into 

1099 

1100 Returns the formatted phone number. 

1101 """ 

1102 if numobj.national_number == 0: 

1103 # Unparseable numbers that kept their raw input just use that, unless default country was 

1104 # specified and the format is E164. In that case, we prepend the raw input with the country 

1105 # code 

1106 raw_input = numobj.raw_input or "" 

1107 if (len(raw_input) > 0 and 

1108 numobj.country_code is not None and 

1109 numobj.country_code_source == CountryCodeSource.FROM_DEFAULT_COUNTRY and 

1110 num_format == PhoneNumberFormat.E164): 

1111 return _prefix_number_with_country_calling_code(numobj.country_code, num_format, raw_input) 

1112 elif len(raw_input) > 0 or numobj.country_code is None: 

1113 return numobj.raw_input 

1114 country_calling_code = numobj.country_code 

1115 nsn = national_significant_number(numobj) 

1116 if num_format == PhoneNumberFormat.E164: 

1117 # Early exit for E164 case (even if the country calling code is 

1118 # invalid) since no formatting of the national number needs to be 

1119 # applied. Extensions are not formatted. 

1120 return _prefix_number_with_country_calling_code(country_calling_code, num_format, nsn) 

1121 if not _has_valid_country_calling_code(country_calling_code): 

1122 return nsn 

1123 # Note region_code_for_country_code() is used because formatting 

1124 # information for regions which share a country calling code is contained 

1125 # by only one region for performance reasons. For example, for NANPA 

1126 # regions it will be contained in the metadata for US. 

1127 region_code = region_code_for_country_code(country_calling_code) 

1128 # Metadata cannot be None because the country calling code is valid (which 

1129 # means that the region code cannot be ZZ and must be one of our supported 

1130 # region codes). 

1131 metadata = PhoneMetadata.metadata_for_region_or_calling_code(country_calling_code, region_code.upper()) 

1132 formatted_number = _format_nsn(nsn, metadata, num_format) 

1133 formatted_number = _maybe_append_formatted_extension(numobj, 

1134 metadata, 

1135 num_format, 

1136 formatted_number) 

1137 return _prefix_number_with_country_calling_code(country_calling_code, 

1138 num_format, 

1139 formatted_number) 

1140 

1141 

1142def format_by_pattern(numobj, number_format, user_defined_formats): 

1143 """Formats a phone number using client-defined formatting rules. 

1144 

1145 Note that if the phone number has a country calling code of zero or an 

1146 otherwise invalid country calling code, we cannot work out things like 

1147 whether there should be a national prefix applied, or how to format 

1148 extensions, so we return the national significant number with no 

1149 formatting applied. 

1150 

1151 Arguments: 

1152 numobj -- The phone number to be formatted 

1153 number_format -- The format the phone number should be formatted into, 

1154 as a PhoneNumberFormat value. 

1155 user_defined_formats -- formatting rules specified by clients, as a list 

1156 of NumberFormat objects. 

1157 

1158 Returns the formatted phone number. 

1159 """ 

1160 country_code = numobj.country_code 

1161 nsn = national_significant_number(numobj) 

1162 if not _has_valid_country_calling_code(country_code): 

1163 return nsn 

1164 # Note region_code_for_country_code() is used because formatting 

1165 # information for regions which share a country calling code is contained 

1166 # by only one region for performance reasons. For example, for NANPA 

1167 # regions it will be contained in the metadata for US. 

1168 region_code = region_code_for_country_code(country_code) 

1169 # Metadata cannot be None because the country calling code is valid. 

1170 metadata = PhoneMetadata.metadata_for_region_or_calling_code(country_code, region_code) 

1171 

1172 formatted_number = U_EMPTY_STRING 

1173 formatting_pattern = _choose_formatting_pattern_for_number(user_defined_formats, nsn) 

1174 if formatting_pattern is None: 

1175 # If no pattern above is matched, we format the number as a whole. 

1176 formatted_number = nsn 

1177 else: 

1178 num_format_copy = _copy_number_format(formatting_pattern) 

1179 # Before we do a replacement of the national prefix pattern $NP with 

1180 # the national prefix, we need to copy the rule so that subsequent 

1181 # replacements for different numbers have the appropriate national 

1182 # prefix. 

1183 np_formatting_rule = formatting_pattern.national_prefix_formatting_rule 

1184 if np_formatting_rule: 

1185 national_prefix = metadata.national_prefix 

1186 if national_prefix: 

1187 # Replace $NP with national prefix and $FG with the first 

1188 # group (\1) matcher. 

1189 np_formatting_rule = np_formatting_rule.replace(_NP_STRING, national_prefix) 

1190 np_formatting_rule = np_formatting_rule.replace(_FG_STRING, unicod("\\1")) 

1191 num_format_copy.national_prefix_formatting_rule = np_formatting_rule 

1192 else: 

1193 # We don't want to have a rule for how to format the national 

1194 # prefix if there isn't one. 

1195 num_format_copy.national_prefix_formatting_rule = None 

1196 formatted_number = _format_nsn_using_pattern(nsn, num_format_copy, number_format) 

1197 formatted_number = _maybe_append_formatted_extension(numobj, 

1198 metadata, 

1199 number_format, 

1200 formatted_number) 

1201 formatted_number = _prefix_number_with_country_calling_code(country_code, 

1202 number_format, 

1203 formatted_number) 

1204 return formatted_number 

1205 

1206 

1207def format_national_number_with_carrier_code(numobj, carrier_code): 

1208 """Format a number in national format for dialing using the specified carrier. 

1209 

1210 The carrier-code will always be used regardless of whether the phone 

1211 number already has a preferred domestic carrier code stored. If 

1212 carrier_code contains an empty string, returns the number in national 

1213 format without any carrier code. 

1214 

1215 Arguments: 

1216 numobj -- The phone number to be formatted 

1217 carrier_code -- The carrier selection code to be used 

1218 

1219 Returns the formatted phone number in national format for dialing using 

1220 the carrier as specified in the carrier_code. 

1221 """ 

1222 country_code = numobj.country_code 

1223 nsn = national_significant_number(numobj) 

1224 if not _has_valid_country_calling_code(country_code): 

1225 return nsn 

1226 # Note region_code_for_country_code() is used because formatting 

1227 # information for regions which share a country calling code is contained 

1228 # by only one region for performance reasons. For example, for NANPA 

1229 # regions it will be contained in the metadata for US. 

1230 region_code = region_code_for_country_code(country_code) 

1231 # Metadata cannot be None because the country calling code is valid 

1232 metadata = PhoneMetadata.metadata_for_region_or_calling_code(country_code, region_code) 

1233 formatted_number = _format_nsn(nsn, 

1234 metadata, 

1235 PhoneNumberFormat.NATIONAL, 

1236 carrier_code) 

1237 formatted_number = _maybe_append_formatted_extension(numobj, 

1238 metadata, 

1239 PhoneNumberFormat.NATIONAL, 

1240 formatted_number) 

1241 formatted_number = _prefix_number_with_country_calling_code(country_code, 

1242 PhoneNumberFormat.NATIONAL, 

1243 formatted_number) 

1244 return formatted_number 

1245 

1246 

1247def format_national_number_with_preferred_carrier_code(numobj, fallback_carrier_code): 

1248 """Formats a phone number in national format for dialing using the carrier 

1249 as specified in the preferred_domestic_carrier_code field of the 

1250 PhoneNumber object passed in. If that is missing, use the 

1251 fallback_carrier_code passed in instead. If there is no 

1252 preferred_domestic_carrier_code, and the fallback_carrier_code contains an 

1253 empty string, return the number in national format without any carrier 

1254 code. 

1255 

1256 Use format_national_number_with_carrier_code instead if the carrier code 

1257 passed in should take precedence over the number's 

1258 preferred_domestic_carrier_code when formatting. 

1259 

1260 Arguments: 

1261 numobj -- The phone number to be formatted 

1262 carrier_code -- The carrier selection code to be used, if none is found in the 

1263 phone number itself. 

1264 

1265 Returns the formatted phone number in national format for dialing using 

1266 the number's preferred_domestic_carrier_code, or the fallback_carrier_code 

1267 pass in if none is found. 

1268 """ 

1269 # Historically, we set this to an empty string when parsing with raw input 

1270 # if none was found in the input string. However, this doesn't result in a 

1271 # number we can dial. For this reason, we treat the empty string the same 

1272 # as if it isn't set at all. 

1273 if (numobj.preferred_domestic_carrier_code is not None and 

1274 len(numobj.preferred_domestic_carrier_code) > 0): 

1275 carrier_code = numobj.preferred_domestic_carrier_code 

1276 else: 

1277 carrier_code = fallback_carrier_code 

1278 return format_national_number_with_carrier_code(numobj, carrier_code) 

1279 

1280 

1281def format_number_for_mobile_dialing(numobj, region_calling_from, with_formatting): 

1282 """Returns a number formatted in such a way that it can be dialed from a 

1283 mobile phone in a specific region. 

1284 

1285 If the number cannot be reached from the region (e.g. some countries block 

1286 toll-free numbers from being called outside of the country), the method 

1287 returns an empty string. 

1288 

1289 Arguments: 

1290 numobj -- The phone number to be formatted 

1291 region_calling_from -- The region where the call is being placed. 

1292 

1293 with_formatting -- whether the number should be returned with formatting 

1294 symbols, such as spaces and dashes. 

1295 

1296 Returns the formatted phone number. 

1297 """ 

1298 country_calling_code = numobj.country_code 

1299 if not _has_valid_country_calling_code(country_calling_code): 

1300 if numobj.raw_input is None: 

1301 return U_EMPTY_STRING 

1302 else: 

1303 return numobj.raw_input 

1304 formatted_number = U_EMPTY_STRING 

1305 # Clear the extension, as that part cannot normally be dialed together with the main number. 

1306 numobj_no_ext = PhoneNumber() 

1307 numobj_no_ext.merge_from(numobj) 

1308 numobj_no_ext.extension = None 

1309 region_code = region_code_for_country_code(country_calling_code) 

1310 numobj_type = number_type(numobj_no_ext) 

1311 is_valid_number = (numobj_type != PhoneNumberType.UNKNOWN) 

1312 if region_calling_from == region_code: 

1313 is_fixed_line_or_mobile = ((numobj_type == PhoneNumberType.FIXED_LINE) or 

1314 (numobj_type == PhoneNumberType.MOBILE) or 

1315 (numobj_type == PhoneNumberType.FIXED_LINE_OR_MOBILE)) 

1316 # Carrier codes may be needed in some countries. We handle this here. 

1317 if region_code == "BR" and is_fixed_line_or_mobile: 

1318 # Historically, we set this to an empty string when parsing with 

1319 # raw input if none was found in the input string. However, this 

1320 # doesn't result in a number we can dial. For this reason, we 

1321 # treat the empty string the same as if it isn't set at all. 

1322 if (numobj_no_ext.preferred_domestic_carrier_code is not None and 

1323 len(numobj_no_ext.preferred_domestic_carrier_code) > 0): 

1324 formatted_number = format_national_number_with_preferred_carrier_code(numobj_no_ext, "") 

1325 else: 

1326 # Brazilian fixed line and mobile numbers need to be dialed with a 

1327 # carrier code when called within Brazil. Without that, most of 

1328 # the carriers won't connect the call. Because of that, we return 

1329 # an empty string here. 

1330 formatted_number = U_EMPTY_STRING 

1331 elif country_calling_code == _NANPA_COUNTRY_CODE: 

1332 # For NANPA countries, we output international format for numbers 

1333 # that can be dialed internationally, since that always works, 

1334 # except for numbers which might potentially be short numbers, 

1335 # which are always dialled in national format. 

1336 metadata = PhoneMetadata.metadata_for_region(region_calling_from) 

1337 assert metadata is not None # due to _has_valid_country_calling_code() check 

1338 if (can_be_internationally_dialled(numobj_no_ext) and 

1339 _test_number_length(national_significant_number(numobj_no_ext), 

1340 metadata) != ValidationResult.TOO_SHORT): 

1341 formatted_number = format_number(numobj_no_ext, PhoneNumberFormat.INTERNATIONAL) 

1342 else: 

1343 formatted_number = format_number(numobj_no_ext, PhoneNumberFormat.NATIONAL) 

1344 else: 

1345 # For non-geographical countries, and Mexican, Chilean, and Uzbek 

1346 # fixed line and mobile numbers, we output international format for 

1347 # numbers that can be dialed internationally as that always works. 

1348 if ((region_code == REGION_CODE_FOR_NON_GEO_ENTITY or 

1349 ((region_code == unicod("MX") or region_code == unicod("CL") or 

1350 region_code == unicod("UZ")) and 

1351 is_fixed_line_or_mobile)) and 

1352 can_be_internationally_dialled(numobj_no_ext)): 

1353 # MX fixed line and mobile numbers should always be formatted 

1354 # in international format, even when dialed within MX. For 

1355 # national format to work, a carrier code needs to be used, 

1356 # and the correct carrier code depends on if the caller and 

1357 # callee are from the same local area. It is trickier to get 

1358 # that to work correctly than using international format, 

1359 # which is tested to work fine on all carriers. 

1360 # CL fixed line numbers need the national prefix when dialing 

1361 # in the national format, but don't have it when used for 

1362 # display. The reverse is true for mobile numbers. As a 

1363 # result, we output them in the international format to make 

1364 # it work. 

1365 # UZ mobile and fixed-line numbers have to be formatted in 

1366 # international format or prefixed with special codes like 03, 

1367 # 04 (for fixed-line) and 05 (for mobile) for dialling 

1368 # successfully from mobile devices. As we do not have complete 

1369 # information on special codes and to be consistent with 

1370 # formatting across all phone types we return the number in 

1371 # international format here. 

1372 formatted_number = format_number(numobj_no_ext, PhoneNumberFormat.INTERNATIONAL) 

1373 else: 

1374 formatted_number = format_number(numobj_no_ext, PhoneNumberFormat.NATIONAL) 

1375 elif is_valid_number and can_be_internationally_dialled(numobj_no_ext): 

1376 # We assume that short numbers are not diallable from outside their 

1377 # region, so if a number is not a valid regular length phone number, 

1378 # we treat it as if it cannot be internationally dialled. 

1379 if with_formatting: 

1380 return format_number(numobj_no_ext, PhoneNumberFormat.INTERNATIONAL) 

1381 else: 

1382 return format_number(numobj_no_ext, PhoneNumberFormat.E164) 

1383 

1384 if with_formatting: 

1385 return formatted_number 

1386 else: 

1387 return normalize_diallable_chars_only(formatted_number) 

1388 

1389 

1390def format_out_of_country_calling_number(numobj, region_calling_from): 

1391 """Formats a phone number for out-of-country dialing purposes. 

1392 

1393 If no region_calling_from is supplied, we format the number in its 

1394 INTERNATIONAL format. If the country calling code is the same as that of 

1395 the region where the number is from, then NATIONAL formatting will be 

1396 applied. 

1397 

1398 If the number itself has a country calling code of zero or an otherwise 

1399 invalid country calling code, then we return the number with no formatting 

1400 applied. 

1401 

1402 Note this function takes care of the case for calling inside of NANPA and 

1403 between Russia and Kazakhstan (who share the same country calling 

1404 code). In those cases, no international prefix is used. For regions which 

1405 have multiple international prefixes, the number in its INTERNATIONAL 

1406 format will be returned instead. 

1407 

1408 Arguments: 

1409 numobj -- The phone number to be formatted 

1410 region_calling_from -- The region where the call is being placed 

1411 

1412 Returns the formatted phone number 

1413 """ 

1414 if not _is_valid_region_code(region_calling_from): 

1415 return format_number(numobj, PhoneNumberFormat.INTERNATIONAL) 

1416 country_code = numobj.country_code 

1417 nsn = national_significant_number(numobj) 

1418 if not _has_valid_country_calling_code(country_code): 

1419 return nsn 

1420 if country_code == _NANPA_COUNTRY_CODE: 

1421 if is_nanpa_country(region_calling_from): 

1422 # For NANPA regions, return the national format for these regions 

1423 # but prefix it with the country calling code. 

1424 return (unicod(country_code) + U_SPACE + 

1425 format_number(numobj, PhoneNumberFormat.NATIONAL)) 

1426 elif country_code == country_code_for_valid_region(region_calling_from): 

1427 # If regions share a country calling code, the country calling code 

1428 # need not be dialled. This also applies when dialling within a 

1429 # region, so this if clause covers both these cases. Technically this 

1430 # is the case for dialling from La Reunion to other overseas 

1431 # departments of France (French Guiana, Martinique, Guadeloupe), but 

1432 # not vice versa - so we don't cover this edge case for now and for 

1433 # those cases return the version including country calling code. 

1434 # Details here: 

1435 # http://www.petitfute.com/voyage/225-info-pratiques-reunion 

1436 return format_number(numobj, PhoneNumberFormat.NATIONAL) 

1437 

1438 # Metadata cannot be None because we checked '_is_valid_region_code()' above. 

1439 metadata_for_region_calling_from = PhoneMetadata.metadata_for_region_or_calling_code(country_code, region_calling_from.upper()) 

1440 international_prefix = metadata_for_region_calling_from.international_prefix 

1441 

1442 # In general, if there is a preferred international prefix, use that. Otherwise, for regions 

1443 # that have multiple international prefixes, the international format of the number is 

1444 # returned since we would not know which one to use. 

1445 i18n_prefix_for_formatting = U_EMPTY_STRING 

1446 if metadata_for_region_calling_from.preferred_international_prefix is not None: 

1447 i18n_prefix_for_formatting = metadata_for_region_calling_from.preferred_international_prefix 

1448 elif fullmatch(_SINGLE_INTERNATIONAL_PREFIX, international_prefix): 

1449 i18n_prefix_for_formatting = international_prefix 

1450 

1451 region_code = region_code_for_country_code(country_code) 

1452 # Metadata cannot be None because the country calling code is valid. 

1453 metadata_for_region = PhoneMetadata.metadata_for_region_or_calling_code(country_code, region_code.upper()) 

1454 formatted_national_number = _format_nsn(nsn, 

1455 metadata_for_region, 

1456 PhoneNumberFormat.INTERNATIONAL) 

1457 formatted_number = _maybe_append_formatted_extension(numobj, 

1458 metadata_for_region, 

1459 PhoneNumberFormat.INTERNATIONAL, 

1460 formatted_national_number) 

1461 if len(i18n_prefix_for_formatting) > 0: 

1462 formatted_number = (i18n_prefix_for_formatting + U_SPACE + 

1463 unicod(country_code) + U_SPACE + formatted_number) 

1464 else: 

1465 formatted_number = _prefix_number_with_country_calling_code(country_code, 

1466 PhoneNumberFormat.INTERNATIONAL, 

1467 formatted_number) 

1468 return formatted_number 

1469 

1470 

1471def format_in_original_format(numobj, region_calling_from): 

1472 """Formats a phone number using the original phone number format 

1473 (e.g. INTERNATIONAL or NATIONAL) that the number is parsed from, provided 

1474 that the number has been parsed with parse(.., keep_raw_input=True). 

1475 Otherwise the number will be formatted in NATIONAL format. 

1476 

1477 The original format is embedded in the country_code_source field of the 

1478 PhoneNumber object passed in, which is only set when parsing keeps the raw 

1479 input. When we don't have a formatting pattern for the number, the method 

1480 falls back to returning the raw input. 

1481 

1482 Note this method guarantees no digit will be inserted, removed or modified 

1483 as a result of formatting. 

1484 

1485 Arguments: 

1486 number -- The phone number that needs to be formatted in its original 

1487 number format 

1488 region_calling_from -- The region whose IDD needs to be prefixed if the 

1489 original number has one. 

1490 

1491 Returns the formatted phone number in its original number format. 

1492 """ 

1493 format_rule = _choose_formatting_pattern_for_numobj(numobj) 

1494 if (numobj.raw_input is not None and format_rule is None): 

1495 # We check if we have the formatting pattern because without that, we 

1496 # might format the number as a group without national prefix. 

1497 return numobj.raw_input 

1498 if numobj.country_code_source is CountryCodeSource.UNSPECIFIED: 

1499 return format_number(numobj, PhoneNumberFormat.NATIONAL) 

1500 

1501 formatted_number = _format_original_allow_mods(numobj, region_calling_from, format_rule) 

1502 num_raw_input = numobj.raw_input 

1503 # If no digit is inserted/removed/modified as a result of our formatting, 

1504 # we return the formatted phone number; otherwise we return the raw input 

1505 # the user entered. 

1506 if (formatted_number is not None and num_raw_input): 

1507 normalized_formatted_number = normalize_diallable_chars_only(formatted_number) 

1508 normalized_raw_input = normalize_diallable_chars_only(num_raw_input) 

1509 if normalized_formatted_number != normalized_raw_input: 

1510 formatted_number = num_raw_input 

1511 return formatted_number 

1512 

1513 

1514def _format_original_allow_mods(numobj, region_calling_from, format_rule): 

1515 if (numobj.country_code_source == CountryCodeSource.FROM_NUMBER_WITH_PLUS_SIGN): 

1516 return format_number(numobj, PhoneNumberFormat.INTERNATIONAL) 

1517 elif numobj.country_code_source == CountryCodeSource.FROM_NUMBER_WITH_IDD: 

1518 return format_out_of_country_calling_number(numobj, region_calling_from) 

1519 elif (numobj.country_code_source == CountryCodeSource.FROM_NUMBER_WITHOUT_PLUS_SIGN): 

1520 return format_number(numobj, PhoneNumberFormat.INTERNATIONAL)[1:] 

1521 else: 

1522 region_code = region_code_for_country_code(numobj.country_code) 

1523 # We strip non-digits from the NDD here, and from the raw input later, so that we can 

1524 # compare them easily. 

1525 national_prefix = ndd_prefix_for_region(region_code, True) # strip non-digits 

1526 national_format = format_number(numobj, PhoneNumberFormat.NATIONAL) 

1527 if (national_prefix is None or len(national_prefix) == 0): 

1528 # If the region doesn't have a national prefix at all, we can 

1529 # safely return the national format without worrying about a 

1530 # national prefix being added. 

1531 return national_format 

1532 # Otherwise, we check if the original number was entered with a national prefix. 

1533 if (_raw_input_contains_national_prefix(numobj.raw_input, national_prefix, region_code)): 

1534 # If so, we can safely return the national format. 

1535 return national_format 

1536 # The format rule could still be null here if the national number was 

1537 # 0 and there was no raw input (this should not be possible for 

1538 # numbers generated by the phonenumber library as they would also not 

1539 # have a country calling code and we would have exited earlier). 

1540 if format_rule is None: 

1541 return national_format 

1542 # When the format we apply to this number doesn't contain national 

1543 # prefix, we can just return the national format. 

1544 # TODO: Refactor the code below with the code in isNationalPrefixPresentIfRequired. 

1545 candidate_national_prefix_rule = format_rule.national_prefix_formatting_rule 

1546 # We assume that the first-group symbol will never be _before_ the national prefix. 

1547 if candidate_national_prefix_rule is None: 

1548 return national_format 

1549 index_of_first_group = candidate_national_prefix_rule.find("\\1") 

1550 if (index_of_first_group <= 0): 

1551 return national_format 

1552 candidate_national_prefix_rule = candidate_national_prefix_rule[:index_of_first_group] 

1553 candidate_national_prefix_rule = normalize_digits_only(candidate_national_prefix_rule) 

1554 if len(candidate_national_prefix_rule) == 0: 

1555 # National prefix not used when formatting this number. 

1556 return national_format 

1557 # Otherwise, we need to remove the national prefix from our output. 

1558 new_format_rule = _copy_number_format(format_rule) 

1559 new_format_rule.national_prefix_formatting_rule = None 

1560 return format_by_pattern(numobj, PhoneNumberFormat.NATIONAL, [new_format_rule]) 

1561 

1562 

1563def _raw_input_contains_national_prefix(raw_input, national_prefix, region_code): 

1564 """Check if raw_input, which is assumed to be in the national format, has a 

1565 national prefix. The national prefix is assumed to be in digits-only 

1566 form.""" 

1567 nnn = normalize_digits_only(raw_input) 

1568 if nnn.startswith(national_prefix): 

1569 try: 

1570 # Some Japanese numbers (e.g. 00777123) might be mistaken to 

1571 # contain the national prefix when written without it 

1572 # (e.g. 0777123) if we just do prefix matching. To tackle that, we 

1573 # check the validity of the number if the assumed national prefix 

1574 # is removed (777123 won't be valid in Japan). 

1575 return is_valid_number(parse(nnn[len(national_prefix):], region_code)) 

1576 except NumberParseException: 

1577 return False 

1578 return False 

1579 

1580 

1581def _choose_formatting_pattern_for_numobj(numobj): 

1582 country_code = numobj.country_code 

1583 phone_number_region = region_code_for_country_code(country_code) 

1584 metadata = PhoneMetadata.metadata_for_region_or_calling_code(country_code, phone_number_region) 

1585 if metadata is None: 

1586 return None 

1587 national_number = national_significant_number(numobj) 

1588 return _choose_formatting_pattern_for_number(metadata.number_format, national_number) 

1589 

1590 

1591def _choose_formatting_pattern_for_number(available_formats, national_number): 

1592 for num_format in available_formats: 

1593 size = len(num_format.leading_digits_pattern) 

1594 # We always use the last leading_digits_pattern, as it is the most detailed. 

1595 if size > 0: 

1596 ld_pattern = re_compile(num_format.leading_digits_pattern[-1]) 

1597 ld_match = ld_pattern.match(national_number) 

1598 if size == 0 or ld_match: 

1599 format_pattern = re_compile(num_format.pattern) 

1600 if fullmatch(format_pattern, national_number): 

1601 return num_format 

1602 return None 

1603 

1604 

1605def format_out_of_country_keeping_alpha_chars(numobj, region_calling_from): 

1606 """Formats a phone number for out-of-country dialing purposes. 

1607 

1608 Note that in this version, if the number was entered originally using 

1609 alpha characters and this version of the number is stored in raw_input, 

1610 this representation of the number will be used rather than the digit 

1611 representation. Grouping information, as specified by characters such as 

1612 "-" and " ", will be retained. 

1613 

1614 Caveats: 

1615 

1616 - This will not produce good results if the country calling code is both 

1617 present in the raw input _and_ is the start of the national 

1618 number. This is not a problem in the regions which typically use alpha 

1619 numbers. 

1620 

1621 - This will also not produce good results if the raw input has any 

1622 grouping information within the first three digits of the national 

1623 number, and if the function needs to strip preceding digits/words in 

1624 the raw input before these digits. Normally people group the first 

1625 three digits together so this is not a huge problem - and will be fixed 

1626 if it proves to be so. 

1627 

1628 Arguments: 

1629 numobj -- The phone number that needs to be formatted. 

1630 region_calling_from -- The region where the call is being placed. 

1631 

1632 Returns the formatted phone number 

1633 """ 

1634 num_raw_input = numobj.raw_input 

1635 # If there is no raw input, then we can't keep alpha characters because there aren't any. 

1636 # In this case, we return format_out_of_country_calling_number. 

1637 if num_raw_input is None or len(num_raw_input) == 0: 

1638 return format_out_of_country_calling_number(numobj, region_calling_from) 

1639 country_code = numobj.country_code 

1640 if not _has_valid_country_calling_code(country_code): 

1641 return num_raw_input 

1642 # Strip any prefix such as country calling code, IDD, that was present. We 

1643 # do this by comparing the number in raw_input with the parsed number. To 

1644 # do this, first we normalize punctuation. We retain number grouping 

1645 # symbols such as " " only. 

1646 num_raw_input = _normalize_helper(num_raw_input, 

1647 _ALL_PLUS_NUMBER_GROUPING_SYMBOLS, 

1648 True) 

1649 # Now we trim everything before the first three digits in the parsed 

1650 # number. We choose three because all valid alpha numbers have 3 digits at 

1651 # the start - if it does not, then we don't trim anything at 

1652 # all. Similarly, if the national number was less than three digits, we 

1653 # don't trim anything at all. 

1654 national_number = national_significant_number(numobj) 

1655 if len(national_number) > 3: 

1656 first_national_number_digit = num_raw_input.find(national_number[:3]) 

1657 if first_national_number_digit != -1: 

1658 num_raw_input = num_raw_input[first_national_number_digit:] 

1659 

1660 metadata_for_region_calling_from = PhoneMetadata.metadata_for_region(region_calling_from.upper(), None) 

1661 if country_code == _NANPA_COUNTRY_CODE: 

1662 if is_nanpa_country(region_calling_from): 

1663 return unicod(country_code) + U_SPACE + num_raw_input 

1664 elif (metadata_for_region_calling_from is not None and 

1665 country_code == country_code_for_region(region_calling_from)): 

1666 formatting_pattern = _choose_formatting_pattern_for_number(metadata_for_region_calling_from.number_format, 

1667 national_number) 

1668 if formatting_pattern is None: 

1669 # If no pattern above is matched, we format the original input 

1670 return num_raw_input 

1671 new_format = _copy_number_format(formatting_pattern) 

1672 # The first group is the first group of digits that the user 

1673 # wrote together. 

1674 new_format.pattern = u("(\\d+)(.*)") 

1675 # Here we just concatenate them back together after the national 

1676 # prefix has been fixed. 

1677 new_format.format = u(r"\1\2") 

1678 # Now we format using this pattern instead of the default pattern, 

1679 # but with the national prefix prefixed if necessary. 

1680 # This will not work in the cases where the pattern (and not the 

1681 # leading digits) decide whether a national prefix needs to be used, 

1682 # since we have overridden the pattern to match anything, but that is 

1683 # not the case in the metadata to date. 

1684 return _format_nsn_using_pattern(num_raw_input, 

1685 new_format, 

1686 PhoneNumberFormat.NATIONAL) 

1687 i18n_prefix_for_formatting = U_EMPTY_STRING 

1688 # If an unsupported region-calling-from is entered, or a country with 

1689 # multiple international prefixes, the international format of the number 

1690 # is returned, unless there is a preferred international prefix. 

1691 if metadata_for_region_calling_from is not None: 

1692 international_prefix = metadata_for_region_calling_from.international_prefix 

1693 i18n_match = fullmatch(_SINGLE_INTERNATIONAL_PREFIX, international_prefix) 

1694 if i18n_match: 

1695 i18n_prefix_for_formatting = international_prefix 

1696 else: 

1697 i18n_prefix_for_formatting = metadata_for_region_calling_from.preferred_international_prefix 

1698 

1699 region_code = region_code_for_country_code(country_code) 

1700 # Metadata cannot be None because the country calling code is valid. 

1701 metadata_for_region = PhoneMetadata.metadata_for_region_or_calling_code(country_code, region_code) 

1702 # Strip any extension 

1703 extension, stripped_number = _maybe_strip_extension(num_raw_input) 

1704 # Append the formatted extension 

1705 formatted_number = _maybe_append_formatted_extension(numobj, 

1706 metadata_for_region, 

1707 PhoneNumberFormat.INTERNATIONAL, 

1708 stripped_number) 

1709 if i18n_prefix_for_formatting: 

1710 formatted_number = (i18n_prefix_for_formatting + U_SPACE + 

1711 unicod(country_code) + U_SPACE + formatted_number) 

1712 else: 

1713 # Invalid region entered as country-calling-from (so no metadata was 

1714 # found for it) or the region chosen has multiple international 

1715 # dialling prefixes. 

1716 formatted_number = _prefix_number_with_country_calling_code(country_code, 

1717 PhoneNumberFormat.INTERNATIONAL, 

1718 formatted_number) 

1719 return formatted_number 

1720 

1721 

1722def national_significant_number(numobj): 

1723 """Gets the national significant number of a phone number. 

1724 

1725 Note that a national significant number doesn't contain a national prefix 

1726 or any formatting. 

1727 

1728 Arguments: 

1729 numobj -- The PhoneNumber object for which the national significant number 

1730 is needed. 

1731 

1732 Returns the national significant number of the PhoneNumber object passed 

1733 in. 

1734 """ 

1735 # If leading zero(s) have been set, we prefix this now. Note this is not a 

1736 # national prefix. 

1737 national_number = U_EMPTY_STRING 

1738 if numobj.italian_leading_zero: 

1739 num_zeros = numobj.number_of_leading_zeros 

1740 if num_zeros is None: 

1741 num_zeros = 1 

1742 if num_zeros > 0: 

1743 national_number = U_ZERO * num_zeros 

1744 national_number += str(numobj.national_number) 

1745 return national_number 

1746 

1747 

1748def _prefix_number_with_country_calling_code(country_code, num_format, formatted_number): 

1749 """A helper function that is used by format_number and format_by_pattern.""" 

1750 if num_format == PhoneNumberFormat.E164: 

1751 return _PLUS_SIGN + unicod(country_code) + formatted_number 

1752 elif num_format == PhoneNumberFormat.INTERNATIONAL: 

1753 return _PLUS_SIGN + unicod(country_code) + U_SPACE + formatted_number 

1754 elif num_format == PhoneNumberFormat.RFC3966: 

1755 return _RFC3966_PREFIX + _PLUS_SIGN + unicod(country_code) + U_DASH + formatted_number 

1756 else: 

1757 return formatted_number 

1758 

1759 

1760def _format_nsn(number, metadata, num_format, carrier_code=None): 

1761 """Format a national number.""" 

1762 # Note in some regions, the national number can be written in two 

1763 # completely different ways depending on whether it forms part of the 

1764 # NATIONAL format or INTERNATIONAL format. The num_format parameter here 

1765 # is used to specify which format to use for those cases. If a carrier_code 

1766 # is specified, this will be inserted into the formatted string to replace 

1767 # $CC. 

1768 intl_number_formats = metadata.intl_number_format 

1769 

1770 # When the intl_number_formats exists, we use that to format national 

1771 # number for the INTERNATIONAL format instead of using the 

1772 # number_desc.number_formats. 

1773 if (len(intl_number_formats) == 0 or 

1774 num_format == PhoneNumberFormat.NATIONAL): 

1775 available_formats = metadata.number_format 

1776 else: 

1777 available_formats = metadata.intl_number_format 

1778 formatting_pattern = _choose_formatting_pattern_for_number(available_formats, number) 

1779 if formatting_pattern is None: 

1780 return number 

1781 else: 

1782 return _format_nsn_using_pattern(number, formatting_pattern, num_format, carrier_code) 

1783 

1784 

1785def _format_nsn_using_pattern(national_number, formatting_pattern, number_format, 

1786 carrier_code=None): 

1787 # Note that carrier_code is optional - if None or an empty string, no 

1788 # carrier code replacement will take place. 

1789 number_format_rule = formatting_pattern.format 

1790 m_re = re_compile(formatting_pattern.pattern) 

1791 formatted_national_number = U_EMPTY_STRING 

1792 

1793 if (number_format == PhoneNumberFormat.NATIONAL and carrier_code and 

1794 formatting_pattern.domestic_carrier_code_formatting_rule): 

1795 # Replace the $CC in the formatting rule with the desired 

1796 # carrier code. 

1797 cc_format_rule = formatting_pattern.domestic_carrier_code_formatting_rule 

1798 cc_format_rule = cc_format_rule.replace(_CC_STRING, carrier_code) 

1799 

1800 # Now replace the $FG in the formatting rule with the 

1801 # first group and the carrier code combined in the 

1802 # appropriate way. 

1803 number_format_rule = re.sub(_FIRST_GROUP_PATTERN, 

1804 cc_format_rule, 

1805 number_format_rule, 

1806 count=1) 

1807 formatted_national_number = re.sub(m_re, number_format_rule, national_number) 

1808 else: 

1809 # Use the national prefix formatting rule instead. 

1810 national_prefix_formatting_rule = formatting_pattern.national_prefix_formatting_rule 

1811 if (number_format == PhoneNumberFormat.NATIONAL and 

1812 national_prefix_formatting_rule): 

1813 first_group_rule = re.sub(_FIRST_GROUP_PATTERN, 

1814 national_prefix_formatting_rule, 

1815 number_format_rule, 

1816 count=1) 

1817 formatted_national_number = re.sub(m_re, first_group_rule, national_number) 

1818 else: 

1819 formatted_national_number = re.sub(m_re, number_format_rule, national_number) 

1820 

1821 if number_format == PhoneNumberFormat.RFC3966: 

1822 # Strip any leading punctuation. 

1823 m = _SEPARATOR_PATTERN.match(formatted_national_number) 

1824 if m: 

1825 formatted_national_number = re.sub(_SEPARATOR_PATTERN, U_EMPTY_STRING, formatted_national_number, count=1) 

1826 # Replace the rest with a dash between each number group 

1827 formatted_national_number = re.sub(_SEPARATOR_PATTERN, U_DASH, formatted_national_number) 

1828 

1829 return formatted_national_number 

1830 

1831 

1832def example_number(region_code): 

1833 """Gets a valid number for the specified region. 

1834 

1835 Arguments: 

1836 region_code -- The region for which an example number is needed. 

1837 

1838 Returns a valid fixed-line number for the specified region. Returns None 

1839 when the metadata does not contain such information, or the region 001 is 

1840 passed in. For 001 (representing non-geographical numbers), call 

1841 example_number_for_non_geo_entity instead. 

1842 """ 

1843 return example_number_for_type(region_code, PhoneNumberType.FIXED_LINE) 

1844 

1845 

1846def invalid_example_number(region_code): 

1847 """Gets an invalid number for the specified region. 

1848 

1849 This is useful for unit-testing purposes, where you want to test what 

1850 will happen with an invalid number. Note that the number that is 

1851 returned will always be able to be parsed and will have the correct 

1852 country code. It may also be a valid *short* number/code for this 

1853 region. Validity checking such numbers is handled with shortnumberinfo. 

1854 

1855 Arguments: 

1856 region_code -- The region for which an example number is needed. 

1857 

1858 

1859 Returns an invalid number for the specified region. Returns None when an 

1860 unsupported region or the region 001 (Earth) is passed in. 

1861 """ 

1862 if not _is_valid_region_code(region_code): 

1863 return None 

1864 # We start off with a valid fixed-line number since every country 

1865 # supports this. Alternatively we could start with a different number 

1866 # type, since fixed-line numbers typically have a wide breadth of valid 

1867 # number lengths and we may have to make it very short before we get an 

1868 # invalid number. 

1869 metadata = PhoneMetadata.metadata_for_region(region_code.upper()) 

1870 assert metadata is not None # due to _is_valid_region_code() check 

1871 desc = _number_desc_by_type(metadata, PhoneNumberType.FIXED_LINE) 

1872 if desc is None or desc.example_number is None: 

1873 # This shouldn't happen; we have a test for this. 

1874 return None # pragma no cover 

1875 example_number = desc.example_number 

1876 # Try and make the number invalid. We do this by changing the length. We 

1877 # try reducing the length of the number, since currently no region has a 

1878 # number that is the same length as MIN_LENGTH_FOR_NSN. This is probably 

1879 # quicker than making the number longer, which is another 

1880 # alternative. We could also use the possible number pattern to extract 

1881 # the possible lengths of the number to make this faster, but this 

1882 # method is only for unit-testing so simplicity is preferred to 

1883 # performance. We don't want to return a number that can't be parsed, 

1884 # so we check the number is long enough. We try all possible lengths 

1885 # because phone number plans often have overlapping prefixes so the 

1886 # number 123456 might be valid as a fixed-line number, and 12345 as a 

1887 # mobile number. It would be faster to loop in a different order, but we 

1888 # prefer numbers that look closer to real numbers (and it gives us a 

1889 # variety of different lengths for the resulting phone numbers - 

1890 # otherwise they would all be MIN_LENGTH_FOR_NSN digits long.) 

1891 phone_number_length = len(example_number) - 1 

1892 while phone_number_length >= _MIN_LENGTH_FOR_NSN: 

1893 number_to_try = example_number[:phone_number_length] 

1894 try: 

1895 possibly_valid_number = parse(number_to_try, region_code) 

1896 if not is_valid_number(possibly_valid_number): 

1897 return possibly_valid_number 

1898 except NumberParseException: # pragma no cover 

1899 # Shouldn't happen: we have already checked the length, we know 

1900 # example numbers have only valid digits, and we know the region 

1901 # code is fine. 

1902 pass 

1903 phone_number_length -= 1 

1904 

1905 # We have a test to check that this doesn't happen for any of our 

1906 # supported regions. 

1907 return None # pragma no cover 

1908 

1909 

1910def example_number_for_type(region_code, num_type): 

1911 """Gets a valid number for the specified region and number type. 

1912 

1913 If None is given as the region_code, then the returned number object 

1914 may belong to any country. 

1915 

1916 Arguments: 

1917 region_code -- The region for which an example number is needed, or None. 

1918 num_type -- The type of number that is needed. 

1919 

1920 Returns a valid number for the specified region and type. Returns None 

1921 when the metadata does not contain such information or if an invalid 

1922 region or region 001 was specified. For 001 (representing 

1923 non-geographical numbers), call example_number_for_non_geo_entity instead. 

1924 """ 

1925 if region_code is None: 

1926 return _example_number_anywhere_for_type(num_type) 

1927 # Check the region code is valid. 

1928 if not _is_valid_region_code(region_code): 

1929 return None 

1930 metadata = PhoneMetadata.metadata_for_region(region_code.upper()) 

1931 assert metadata is not None # due to _is_valid_region_code() check 

1932 desc = _number_desc_by_type(metadata, num_type) 

1933 if desc is not None and desc.example_number is not None: 

1934 try: 

1935 return parse(desc.example_number, region_code) 

1936 except NumberParseException: # pragma no cover 

1937 pass 

1938 return None 

1939 

1940 

1941def _example_number_anywhere_for_type(num_type): 

1942 """Gets a valid number for the specified number type (it may belong to any country). 

1943 

1944 Arguments: 

1945 num_type -- The type of number that is needed. 

1946 

1947 Returns a valid number for the specified type. Returns None when the 

1948 metadata does not contain such information. This should only happen when 

1949 no numbers of this type are allocated anywhere in the world anymore. 

1950 """ 

1951 for region_code in SUPPORTED_REGIONS: 

1952 example_numobj = example_number_for_type(region_code, num_type) 

1953 if example_numobj is not None: 

1954 return example_numobj 

1955 # If there wasn't an example number for a region, try the non-geographical entities. 

1956 for country_calling_code in COUNTRY_CODES_FOR_NON_GEO_REGIONS: 

1957 metadata = PhoneMetadata.metadata_for_nongeo_region(country_calling_code, None) 

1958 desc = _number_desc_by_type(metadata, num_type) 

1959 if desc is not None and desc.example_number is not None: 

1960 try: 

1961 return parse(_PLUS_SIGN + unicod(country_calling_code) + desc.example_number, UNKNOWN_REGION) 

1962 except NumberParseException: # pragma no cover 

1963 pass 

1964 

1965 # There are no example numbers of this type for any country in the library. 

1966 return None # pragma no cover 

1967 

1968 

1969def example_number_for_non_geo_entity(country_calling_code): 

1970 """Gets a valid number for the specified country calling code for a non-geographical entity. 

1971 

1972 Arguments: 

1973 country_calling_code -- The country calling code for a non-geographical entity. 

1974 

1975 Returns a valid number for the non-geographical entity. Returns None when 

1976 the metadata does not contain such information, or the country calling 

1977 code passed in does not belong to a non-geographical entity. 

1978 """ 

1979 metadata = PhoneMetadata.metadata_for_nongeo_region(country_calling_code, None) 

1980 if metadata is not None: 

1981 # For geographical entities, fixed-line data is always present. However, for non-geographical 

1982 # entities, this is not the case, so we have to go through different types to find the 

1983 # example number. We don't check fixed-line or personal number since they aren't used by 

1984 # non-geographical entities (if this changes, a unit-test will catch this.) 

1985 for desc in (metadata.mobile, metadata.toll_free, metadata.shared_cost, metadata.voip, 

1986 metadata.voicemail, metadata.uan, metadata.premium_rate): 

1987 try: 

1988 if (desc is not None and desc.example_number is not None): 

1989 return parse(_PLUS_SIGN + unicod(country_calling_code) + desc.example_number, UNKNOWN_REGION) 

1990 except NumberParseException: 

1991 pass 

1992 return None 

1993 

1994 

1995def _maybe_append_formatted_extension(numobj, metadata, num_format, number): 

1996 """Appends the formatted extension of a phone number to formatted number, 

1997 if the phone number had an extension specified. 

1998 """ 

1999 if numobj.extension: 

2000 if num_format == PhoneNumberFormat.RFC3966: 

2001 return number + _RFC3966_EXTN_PREFIX + numobj.extension 

2002 else: 

2003 if metadata.preferred_extn_prefix is not None: 

2004 return number + metadata.preferred_extn_prefix + numobj.extension 

2005 else: 

2006 return number + _DEFAULT_EXTN_PREFIX + numobj.extension 

2007 return number 

2008 

2009 

2010def _number_desc_by_type(metadata, num_type): 

2011 """Return the PhoneNumberDesc of the metadata for the given number type""" 

2012 if num_type == PhoneNumberType.PREMIUM_RATE: 

2013 return metadata.premium_rate 

2014 elif num_type == PhoneNumberType.TOLL_FREE: 

2015 return metadata.toll_free 

2016 elif num_type == PhoneNumberType.MOBILE: 

2017 return metadata.mobile 

2018 elif (num_type == PhoneNumberType.FIXED_LINE or 

2019 num_type == PhoneNumberType.FIXED_LINE_OR_MOBILE): 

2020 return metadata.fixed_line 

2021 elif num_type == PhoneNumberType.SHARED_COST: 

2022 return metadata.shared_cost 

2023 elif num_type == PhoneNumberType.VOIP: 

2024 return metadata.voip 

2025 elif num_type == PhoneNumberType.PERSONAL_NUMBER: 

2026 return metadata.personal_number 

2027 elif num_type == PhoneNumberType.PAGER: 

2028 return metadata.pager 

2029 elif num_type == PhoneNumberType.UAN: 

2030 return metadata.uan 

2031 elif num_type == PhoneNumberType.VOICEMAIL: 

2032 return metadata.voicemail 

2033 else: 

2034 return metadata.general_desc 

2035 

2036 

2037def number_type(numobj): 

2038 """Gets the type of a valid phone number. 

2039 

2040 Arguments: 

2041 numobj -- The PhoneNumber object that we want to know the type of. 

2042 

2043 Returns the type of the phone number, as a PhoneNumberType value; 

2044 returns PhoneNumberType.UNKNOWN if it is invalid. 

2045 """ 

2046 region_code = region_code_for_number(numobj) 

2047 metadata = PhoneMetadata.metadata_for_region_or_calling_code(numobj.country_code, region_code) 

2048 if metadata is None: 

2049 return PhoneNumberType.UNKNOWN 

2050 national_number = national_significant_number(numobj) 

2051 return _number_type_helper(national_number, metadata) 

2052 

2053 

2054def _number_type_helper(national_number, metadata): 

2055 """Return the type of the given number against the metadata""" 

2056 if not _is_number_matching_desc(national_number, metadata.general_desc): 

2057 return PhoneNumberType.UNKNOWN 

2058 if _is_number_matching_desc(national_number, metadata.premium_rate): 

2059 return PhoneNumberType.PREMIUM_RATE 

2060 if _is_number_matching_desc(national_number, metadata.toll_free): 

2061 return PhoneNumberType.TOLL_FREE 

2062 if _is_number_matching_desc(national_number, metadata.shared_cost): 

2063 return PhoneNumberType.SHARED_COST 

2064 if _is_number_matching_desc(national_number, metadata.voip): 

2065 return PhoneNumberType.VOIP 

2066 if _is_number_matching_desc(national_number, metadata.personal_number): 

2067 return PhoneNumberType.PERSONAL_NUMBER 

2068 if _is_number_matching_desc(national_number, metadata.pager): 

2069 return PhoneNumberType.PAGER 

2070 if _is_number_matching_desc(national_number, metadata.uan): 

2071 return PhoneNumberType.UAN 

2072 if _is_number_matching_desc(national_number, metadata.voicemail): 

2073 return PhoneNumberType.VOICEMAIL 

2074 

2075 if _is_number_matching_desc(national_number, metadata.fixed_line): 

2076 if metadata.same_mobile_and_fixed_line_pattern: 

2077 return PhoneNumberType.FIXED_LINE_OR_MOBILE 

2078 elif _is_number_matching_desc(national_number, metadata.mobile): 

2079 return PhoneNumberType.FIXED_LINE_OR_MOBILE 

2080 return PhoneNumberType.FIXED_LINE 

2081 

2082 # Otherwise, test to see if the number is mobile. Only do this if certain 

2083 # that the patterns for mobile and fixed line aren't the same. 

2084 if (not metadata.same_mobile_and_fixed_line_pattern and 

2085 _is_number_matching_desc(national_number, metadata.mobile)): 

2086 return PhoneNumberType.MOBILE 

2087 return PhoneNumberType.UNKNOWN 

2088 

2089 

2090def _is_number_matching_desc(national_number, number_desc): 

2091 """Determine if the number matches the given PhoneNumberDesc""" 

2092 # Check if any possible number lengths are present; if so, we use them to avoid checking the 

2093 # validation pattern if they don't match. If they are absent, this means they match the general 

2094 # description, which we have already checked before checking a specific number type. 

2095 if number_desc is None: 

2096 return False 

2097 actual_length = len(national_number) 

2098 possible_lengths = number_desc.possible_length 

2099 if len(possible_lengths) > 0 and actual_length not in possible_lengths: 

2100 return False 

2101 return _match_national_number(national_number, number_desc, False) 

2102 

2103 

2104def is_valid_number(numobj): 

2105 """Tests whether a phone number matches a valid pattern. 

2106 

2107 Note this doesn't verify the number is actually in use, which is 

2108 impossible to tell by just looking at a number itself. It only verifies 

2109 whether the parsed, canonicalised number is valid: not whether a 

2110 particular series of digits entered by the user is diallable from the 

2111 region provided when parsing. For example, the number +41 (0) 78 927 2696 

2112 can be parsed into a number with country code "41" and national 

2113 significant number "789272696". This is valid, while the original string 

2114 is not diallable. 

2115 

2116 Arguments: 

2117 numobj -- The phone number object that we want to validate 

2118 

2119 Returns a boolean that indicates whether the number is of a valid pattern. 

2120 """ 

2121 region_code = region_code_for_number(numobj) 

2122 return is_valid_number_for_region(numobj, region_code) 

2123 

2124 

2125def is_valid_number_for_region(numobj, region_code): 

2126 """Tests whether a phone number is valid for a certain region. 

2127 

2128 Note this doesn't verify the number is actually in use, which is 

2129 impossible to tell by just looking at a number itself. If the country 

2130 calling code is not the same as the country calling code for the region, 

2131 this immediately exits with false. After this, the specific number pattern 

2132 rules for the region are examined. This is useful for determining for 

2133 example whether a particular number is valid for Canada, rather than just 

2134 a valid NANPA number. 

2135 

2136 Warning: In most cases, you want to use is_valid_number instead. For 

2137 example, this method will mark numbers from British Crown dependencies 

2138 such as the Isle of Man as invalid for the region "GB" (United Kingdom), 

2139 since it has its own region code, "IM", which may be undesirable. 

2140 

2141 Arguments: 

2142 numobj -- The phone number object that we want to validate. 

2143 region_code -- The region that we want to validate the phone number for. 

2144 

2145 Returns a boolean that indicates whether the number is of a valid pattern. 

2146 """ 

2147 country_code = numobj.country_code 

2148 if region_code is None: 

2149 return False 

2150 metadata = PhoneMetadata.metadata_for_region_or_calling_code(country_code, region_code.upper()) 

2151 if (metadata is None or 

2152 (region_code != REGION_CODE_FOR_NON_GEO_ENTITY and 

2153 country_code != country_code_for_valid_region(region_code))): 

2154 # Either the region code was invalid, or the country calling code for 

2155 # this number does not match that of the region code. 

2156 return False 

2157 nsn = national_significant_number(numobj) 

2158 return (_number_type_helper(nsn, metadata) != PhoneNumberType.UNKNOWN) 

2159 

2160 

2161def region_code_for_number(numobj): 

2162 """Returns the region where a phone number is from. 

2163 

2164 This could be used for geocoding at the region level. Only guarantees 

2165 correct results for valid, full numbers (not short-codes, or invalid 

2166 numbers). 

2167 

2168 Arguments: 

2169 numobj -- The phone number object whose origin we want to know 

2170 

2171 Returns the region where the phone number is from, or None if no region 

2172 matches this calling code. 

2173 

2174 """ 

2175 country_code = numobj.country_code 

2176 regions = COUNTRY_CODE_TO_REGION_CODE.get(country_code, None) 

2177 if regions is None: 

2178 return None 

2179 

2180 if len(regions) == 1: 

2181 return regions[0] 

2182 else: 

2183 return _region_code_for_number_from_list(numobj, regions) 

2184 

2185 

2186def _region_code_for_number_from_list(numobj, regions): 

2187 """Find the region in a list that matches a number""" 

2188 national_number = national_significant_number(numobj) 

2189 for region_code in regions: 

2190 # If leading_digits is present, use this. Otherwise, do full 

2191 # validation. 

2192 # Metadata cannot be None because the region codes come from 

2193 # the country calling code map. 

2194 metadata = PhoneMetadata.metadata_for_region(region_code.upper(), None) 

2195 if metadata is None: 

2196 continue 

2197 if metadata.leading_digits is not None: 

2198 leading_digit_re = re_compile(metadata.leading_digits) 

2199 match = leading_digit_re.match(national_number) 

2200 if match: 

2201 return region_code 

2202 elif _number_type_helper(national_number, metadata) != PhoneNumberType.UNKNOWN: 

2203 return region_code 

2204 return None 

2205 

2206 

2207def region_code_for_country_code(country_code): 

2208 """Returns the region code that matches a specific country calling code. 

2209 

2210 In the case of no region code being found, UNKNOWN_REGION ('ZZ') will be 

2211 returned. In the case of multiple regions, the one designated in the 

2212 metadata as the "main" region for this calling code will be returned. If 

2213 the country_code entered is valid but doesn't match a specific region 

2214 (such as in the case of non-geographical calling codes like 800) the value 

2215 "001" will be returned (corresponding to the value for World in the UN 

2216 M.49 schema). 

2217 """ 

2218 regions = COUNTRY_CODE_TO_REGION_CODE.get(country_code, None) 

2219 if regions is None: 

2220 return UNKNOWN_REGION 

2221 else: 

2222 return regions[0] 

2223 

2224 

2225def region_codes_for_country_code(country_code): 

2226 """Returns a list with the region codes that match the specific country calling code. 

2227 

2228 For non-geographical country calling codes, the region code 001 is 

2229 returned. Also, in the case of no region code being found, an empty 

2230 list is returned. 

2231 """ 

2232 regions = COUNTRY_CODE_TO_REGION_CODE.get(country_code, None) 

2233 if regions is None: 

2234 return () 

2235 else: 

2236 return regions 

2237 

2238 

2239def country_code_for_region(region_code): 

2240 """Returns the country calling code for a specific region. 

2241 

2242 For example, this would be 1 for the United States, and 64 for New 

2243 Zealand. 

2244 

2245 Arguments: 

2246 region_code -- The region that we want to get the country calling code for. 

2247 

2248 Returns the country calling code for the region denoted by region_code. 

2249 """ 

2250 if not _is_valid_region_code(region_code): 

2251 return 0 

2252 return country_code_for_valid_region(region_code) 

2253 

2254 

2255def country_code_for_valid_region(region_code): 

2256 """Returns the country calling code for a specific region. 

2257 

2258 For example, this would be 1 for the United States, and 64 for New 

2259 Zealand. Assumes the region is already valid. 

2260 

2261 Arguments: 

2262 region_code -- The region that we want to get the country calling code for. 

2263 

2264 Returns the country calling code for the region denoted by region_code. 

2265 """ 

2266 metadata = PhoneMetadata.metadata_for_region(region_code.upper(), None) 

2267 if metadata is None: 

2268 raise Exception("Invalid region code %s" % region_code) 

2269 return metadata.country_code 

2270 

2271 

2272def ndd_prefix_for_region(region_code, strip_non_digits): 

2273 """Returns the national dialling prefix for a specific region. 

2274 

2275 For example, this would be 1 for the United States, and 0 for New 

2276 Zealand. Set strip_non_digits to True to strip symbols like "~" (which 

2277 indicates a wait for a dialling tone) from the prefix returned. If no 

2278 national prefix is present, we return None. 

2279 

2280 Warning: Do not use this method for do-your-own formatting - for some 

2281 regions, the national dialling prefix is used only for certain types of 

2282 numbers. Use the library's formatting functions to prefix the national 

2283 prefix when required. 

2284 

2285 Arguments: 

2286 region_code -- The region that we want to get the dialling prefix for. 

2287 strip_non_digits -- whether to strip non-digits from the national 

2288 dialling prefix. 

2289 

2290 Returns the dialling prefix for the region denoted by region_code. 

2291 """ 

2292 if region_code is None: 

2293 return None 

2294 metadata = PhoneMetadata.metadata_for_region(region_code.upper(), None) 

2295 if metadata is None: 

2296 return None 

2297 national_prefix = metadata.national_prefix 

2298 if national_prefix is None or len(national_prefix) == 0: 

2299 return None 

2300 if strip_non_digits: 

2301 # Note: if any other non-numeric symbols are ever used in national 

2302 # prefixes, these would have to be removed here as well. 

2303 national_prefix = re.sub(U_TILDE, U_EMPTY_STRING, national_prefix) 

2304 return national_prefix 

2305 

2306 

2307def is_nanpa_country(region_code): 

2308 """Checks if this region is a NANPA region. 

2309 

2310 Returns True if region_code is one of the regions under the North American 

2311 Numbering Plan Administration (NANPA). 

2312 """ 

2313 return region_code in _NANPA_REGIONS 

2314 

2315 

2316def is_alpha_number(number): 

2317 """Checks if the number is a valid vanity (alpha) number such as 800 

2318 MICROSOFT. A valid vanity number will start with at least 3 digits and 

2319 will have three or more alpha characters. This does not do region-specific 

2320 checks - to work out if this number is actually valid for a region, it 

2321 should be parsed and methods such as is_possible_number_with_reason() and 

2322 is_valid_number() should be used. 

2323 

2324 Arguments: 

2325 number -- the number that needs to be checked 

2326 

2327 Returns True if the number is a valid vanity number 

2328 """ 

2329 if len(number) > _MAX_INPUT_STRING_LENGTH: 

2330 # Too long to parse, so can't be a valid number; also avoids quadratic 

2331 # time in _maybe_strip_extension() for long runs of separators. 

2332 return False 

2333 if not _is_viable_phone_number(number): 

2334 # Number is too short, or doesn't match the basic phone number pattern. 

2335 return False 

2336 extension, stripped_number = _maybe_strip_extension(number) 

2337 return bool(fullmatch(_VALID_ALPHA_PHONE_PATTERN, stripped_number)) 

2338 

2339 

2340def is_possible_number(numobj): 

2341 """Convenience wrapper around is_possible_number_with_reason. 

2342 

2343 Instead of returning the reason for failure, this method returns true if 

2344 the number is either a possible fully-qualified number (containing the area 

2345 code and country code), or if the number could be a possible local number 

2346 (with a country code, but missing an area code). Local numbers are 

2347 considered possible if they could be possibly dialled in this format: if 

2348 the area code is needed for a call to connect, the number is not considered 

2349 possible without it. 

2350 

2351 Arguments: 

2352 numobj -- the number object that needs to be checked 

2353 

2354 Returns True if the number is possible 

2355 

2356 """ 

2357 result = is_possible_number_with_reason(numobj) 

2358 return (result == ValidationResult.IS_POSSIBLE or 

2359 result == ValidationResult.IS_POSSIBLE_LOCAL_ONLY) 

2360 

2361 

2362def is_possible_number_for_type(numobj, numtype): 

2363 """Convenience wrapper around is_possible_number_for_type_with_reason. 

2364 

2365 Instead of returning the reason for failure, this method returns true if 

2366 the number is either a possible fully-qualified number (containing the area 

2367 code and country code), or if the number could be a possible local number 

2368 (with a country code, but missing an area code). Local numbers are 

2369 considered possible if they could be possibly dialled in this format: if 

2370 the area code is needed for a call to connect, the number is not considered 

2371 possible without it. 

2372 

2373 Arguments: 

2374 numobj -- the number object that needs to be checked 

2375 numtype -- the type we are interested in 

2376 

2377 Returns True if the number is possible 

2378 

2379 """ 

2380 result = is_possible_number_for_type_with_reason(numobj, numtype) 

2381 return (result == ValidationResult.IS_POSSIBLE or 

2382 result == ValidationResult.IS_POSSIBLE_LOCAL_ONLY) 

2383 

2384 

2385def _test_number_length(national_number, metadata, numtype=PhoneNumberType.UNKNOWN): 

2386 """Helper method to check a number against possible lengths for this number, 

2387 and determine whether it matches, or is too short or too long. 

2388 """ 

2389 desc_for_type = _number_desc_by_type(metadata, numtype) 

2390 if desc_for_type is None: 

2391 possible_lengths = metadata.general_desc.possible_length 

2392 local_lengths = () 

2393 else: 

2394 # There should always be "possibleLengths" set for every element. This is declared in the XML 

2395 # schema which is verified by PhoneNumberMetadataSchemaTest. 

2396 # For size efficiency, where a sub-description (e.g. fixed-line) has the same possibleLengths 

2397 # as the parent, this is missing, so we fall back to the general desc (where no numbers of the 

2398 # type exist at all, there is one possible length (-1) which is guaranteed not to match the 

2399 # length of any real phone number). 

2400 possible_lengths = desc_for_type.possible_length 

2401 if len(possible_lengths) == 0: # pragma no cover: Python sub-descs all have possible_length 

2402 possible_lengths = metadata.general_desc.possible_length 

2403 local_lengths = desc_for_type.possible_length_local_only 

2404 

2405 if numtype == PhoneNumberType.FIXED_LINE_OR_MOBILE: 

2406 if not _desc_has_possible_number_data(_number_desc_by_type(metadata, PhoneNumberType.FIXED_LINE)): 

2407 # The rare case has been encountered where no fixedLine data is available (true for some 

2408 # non-geographical entities), so we just check mobile. 

2409 return _test_number_length(national_number, metadata, PhoneNumberType.MOBILE) 

2410 else: 

2411 mobile_desc = _number_desc_by_type(metadata, PhoneNumberType.MOBILE) 

2412 if _desc_has_possible_number_data(mobile_desc): 

2413 # Merge the mobile data in if there was any. We have to make a copy to do this. 

2414 possible_lengths = list(possible_lengths) 

2415 # Note that when adding the possible lengths from mobile, we have to again check they 

2416 # aren't empty since if they are this indicates they are the same as the general desc and 

2417 # should be obtained from there. 

2418 if len(mobile_desc.possible_length) == 0: # pragma no cover: Python sub-descs all have possible_length 

2419 possible_lengths += metadata.general_desc.possible_length 

2420 else: 

2421 possible_lengths += mobile_desc.possible_length 

2422 # The current list is sorted; we need to merge in the new list and re-sort (duplicates 

2423 # are okay). Sorting isn't so expensive because the lists are very small. 

2424 list.sort(possible_lengths) 

2425 

2426 if len(local_lengths) == 0: 

2427 local_lengths = mobile_desc.possible_length_local_only 

2428 else: 

2429 local_lengths = list(local_lengths) 

2430 local_lengths += mobile_desc.possible_length_local_only 

2431 list.sort(local_lengths) 

2432 

2433 # If the type is not supported at all (indicated by a missing PhoneNumberDesc) we return invalid length. 

2434 if desc_for_type is None: 

2435 return ValidationResult.INVALID_LENGTH 

2436 

2437 actual_length = len(national_number) 

2438 # This is safe because there is never an overlap between the possible lengths and the local-only 

2439 # lengths; this is checked at build time. 

2440 if actual_length in local_lengths: 

2441 return ValidationResult.IS_POSSIBLE_LOCAL_ONLY 

2442 

2443 minimum_length = possible_lengths[0] 

2444 if minimum_length == actual_length: 

2445 return ValidationResult.IS_POSSIBLE 

2446 elif minimum_length > actual_length: 

2447 return ValidationResult.TOO_SHORT 

2448 elif possible_lengths[-1] < actual_length: 

2449 return ValidationResult.TOO_LONG 

2450 # We skip the first element; we've already checked it. 

2451 if actual_length in possible_lengths[1:]: 

2452 return ValidationResult.IS_POSSIBLE 

2453 else: 

2454 return ValidationResult.INVALID_LENGTH 

2455 

2456 

2457def is_possible_number_with_reason(numobj): 

2458 """See documentation for is_possible_number_for_type_with_reason""" 

2459 return is_possible_number_for_type_with_reason(numobj, PhoneNumberType.UNKNOWN) 

2460 

2461 

2462def is_possible_number_for_type_with_reason(numobj, numtype): 

2463 """Check whether a phone number is a possible number of a particular type. 

2464 

2465 For types that don't exist in a particular region, this will return a result 

2466 that isn't so useful; it is recommended that you use 

2467 supported_types_for_region or supported_types_for_non_geo_entity 

2468 respectively before calling this method to determine whether you should call 

2469 it for this number at all. 

2470 

2471 This provides a more lenient check than is_valid_number in the following sense: 

2472 

2473 - It only checks the length of phone numbers. In particular, it doesn't 

2474 check starting digits of the number. 

2475 

2476 - For some numbers (particularly fixed-line), many regions have the 

2477 concept of area code, which together with subscriber number constitute 

2478 the national significant number. It is sometimes okay to dial only the 

2479 subscriber number when dialing in the same area. This function will 

2480 return IS_POSSIBLE_LOCAL_ONLY if the subscriber-number-only version is 

2481 passed in. On the other hand, because is_valid_number validates using 

2482 information on both starting digits (for fixed line numbers, that would 

2483 most likely be area codes) and length (obviously includes the length of 

2484 area codes for fixed line numbers), it will return false for the 

2485 subscriber-number-only version. 

2486 

2487 There is a known <a 

2488 href="https://issuetracker.google.com/issues/335892662">issue</a> with this 

2489 method: if a number is possible only in a certain region among several 

2490 regions that share the same country calling code, this method will consider 

2491 only the "main" region. For example, +1310xxxx are valid numbers in 

2492 Canada. However, they are not possible in the US. As a result, this method 

2493 will return IS_POSSIBLE_LOCAL_ONLY for +1310xxxx. 

2494 

2495 Arguments: 

2496 numobj -- The number object that needs to be checked 

2497 numtype -- The type we are interested in 

2498 

2499 Returns a value from ValidationResult which indicates whether the number 

2500 is possible 

2501 """ 

2502 national_number = national_significant_number(numobj) 

2503 country_code = numobj.country_code 

2504 # Note: For regions that share a country calling code, like NANPA numbers, 

2505 # we just use the rules from the default region (US in this case) since the 

2506 # region_code_for_number will not work if the number is possible but not 

2507 # valid. There is in fact one country calling code (290) where the possible 

2508 # number pattern differs between various regions (Saint Helena and Tristan 

2509 # da Cuñha), but this is handled by putting all possible lengths for any 

2510 # country with this country calling code in the metadata for the default 

2511 # region in this case. 

2512 if not _has_valid_country_calling_code(country_code): 

2513 return ValidationResult.INVALID_COUNTRY_CODE 

2514 region_code = region_code_for_country_code(country_code) 

2515 # Metadata cannot be None because the country calling code is valid. 

2516 metadata = PhoneMetadata.metadata_for_region_or_calling_code(country_code, region_code) 

2517 return _test_number_length(national_number, metadata, numtype) 

2518 

2519 

2520def is_possible_number_string(number, region_dialing_from): 

2521 """Check whether a phone number string is a possible number. 

2522 

2523 Takes a number in the form of a string, and the region where the number 

2524 could be dialed from. It provides a more lenient check than 

2525 is_valid_number; see is_possible_number_with_reason() for details. 

2526 

2527 This method first parses the number, then invokes is_possible_number with 

2528 the resultant PhoneNumber object. 

2529 

2530 Arguments: 

2531 number -- The number that needs to be checked, in the form of a string. 

2532 region_dialling_from -- The region that we are expecting the number to be 

2533 dialed from. Note this is different from the region where the 

2534 number belongs. For example, the number +1 650 253 0000 is a 

2535 number that belongs to US. When written in this form, it can be 

2536 dialed from any region. When it is written as 00 1 650 253 0000, 

2537 it can be dialed from any region which uses an international 

2538 dialling prefix of 00. When it is written as 650 253 0000, it 

2539 can only be dialed from within the US, and when written as 253 

2540 0000, it can only be dialed from within a smaller area in the US 

2541 (Mountain View, CA, to be more specific). 

2542 

2543 Returns True if the number is possible 

2544 """ 

2545 try: 

2546 return is_possible_number(parse(number, region_dialing_from)) 

2547 except NumberParseException: 

2548 return False 

2549 

2550 

2551def truncate_too_long_number(numobj): 

2552 """Truncate a number object that is too long. 

2553 

2554 Attempts to extract a valid number from a phone number that is too long 

2555 to be valid, and resets the PhoneNumber object passed in to that valid 

2556 version. If no valid number could be extracted, the PhoneNumber object 

2557 passed in will not be modified. 

2558 

2559 Arguments: 

2560 numobj -- A PhoneNumber object which contains a number that is too long to 

2561 be valid. 

2562 

2563 Returns True if a valid phone number can be successfully extracted. 

2564 """ 

2565 if is_valid_number(numobj): 

2566 return True 

2567 numobj_copy = PhoneNumber() 

2568 numobj_copy.merge_from(numobj) 

2569 national_number = numobj.national_number 

2570 

2571 while not is_valid_number(numobj_copy): 

2572 # Strip a digit off the RHS 

2573 national_number = national_number // 10 

2574 numobj_copy.national_number = national_number 

2575 validation_result = is_possible_number_with_reason(numobj_copy) 

2576 if (validation_result == ValidationResult.TOO_SHORT or 

2577 national_number == 0): 

2578 return False 

2579 # To reach here, numobj_copy is a valid number. Modify the original object 

2580 numobj.national_number = national_number 

2581 return True 

2582 

2583 

2584def _extract_country_code(number): 

2585 """Extracts country calling code from number. 

2586 

2587 Returns a 2-tuple of (country_calling_code, rest_of_number). It assumes 

2588 that the leading plus sign or IDD has already been removed. Returns (0, 

2589 number) if number doesn't start with a valid country calling code. 

2590 """ 

2591 

2592 if len(number) == 0 or number[0] == U_ZERO: 

2593 # Country codes do not begin with a '0'. 

2594 return (0, number) 

2595 for ii in range(1, min(len(number), _MAX_LENGTH_COUNTRY_CODE) + 1): 

2596 try: 

2597 country_code = int(number[:ii]) 

2598 if country_code in COUNTRY_CODE_TO_REGION_CODE: 

2599 return (country_code, number[ii:]) 

2600 except Exception: 

2601 pass 

2602 return (0, number) 

2603 

2604 

2605def _maybe_extract_country_code(number, metadata, keep_raw_input, numobj): 

2606 """Tries to extract a country calling code from a number. 

2607 

2608 This method will return zero if no country calling code is considered to 

2609 be present. Country calling codes are extracted in the following ways: 

2610 

2611 - by stripping the international dialing prefix of the region the person 

2612 is dialing from, if this is present in the number, and looking at the 

2613 next digits 

2614 

2615 - by stripping the '+' sign if present and then looking at the next 

2616 digits 

2617 

2618 - by comparing the start of the number and the country calling code of 

2619 the default region. If the number is not considered possible for the 

2620 numbering plan of the default region initially, but starts with the 

2621 country calling code of this region, validation will be reattempted 

2622 after stripping this country calling code. If this number is considered 

2623 a possible number, then the first digits will be considered the country 

2624 calling code and removed as such. 

2625 

2626 It will raise a NumberParseException if the number starts with a '+' but 

2627 the country calling code supplied after this does not match that of any 

2628 known region. 

2629 

2630 Arguments: 

2631 number -- non-normalized telephone number that we wish to extract a 

2632 country calling code from; may begin with '+' 

2633 metadata -- metadata about the region this number may be from, or None 

2634 keep_raw_input -- True if the country_code_source and 

2635 preferred_carrier_code fields of numobj should be populated. 

2636 numobj -- The PhoneNumber object where the country_code and 

2637 country_code_source need to be populated. Note the country_code 

2638 is always populated, whereas country_code_source is only 

2639 populated when keep_raw_input is True. 

2640 

2641 Returns a 2-tuple containing: 

2642 - the country calling code extracted or 0 if none could be extracted 

2643 - a string holding the national significant number, in the case 

2644 that a country calling code was extracted. If no country calling code 

2645 was extracted, this will be empty. 

2646 """ 

2647 if len(number) == 0: 

2648 return (0, U_EMPTY_STRING) 

2649 full_number = number 

2650 # Set the default prefix to be something that will never match. 

2651 possible_country_idd_prefix = unicod("NonMatch") 

2652 if metadata is not None and metadata.international_prefix is not None: 

2653 possible_country_idd_prefix = metadata.international_prefix 

2654 

2655 country_code_source, full_number = _maybe_strip_i18n_prefix_and_normalize(full_number, 

2656 possible_country_idd_prefix) 

2657 if keep_raw_input: 

2658 numobj.country_code_source = country_code_source 

2659 

2660 if country_code_source != CountryCodeSource.FROM_DEFAULT_COUNTRY: 

2661 if len(full_number) <= _MIN_LENGTH_FOR_NSN: 

2662 raise NumberParseException(NumberParseException.TOO_SHORT_AFTER_IDD, 

2663 "Phone number had an IDD, but after this was not " + 

2664 "long enough to be a viable phone number.") 

2665 potential_country_code, rest_of_number = _extract_country_code(full_number) 

2666 if potential_country_code != 0: 

2667 numobj.country_code = potential_country_code 

2668 return (potential_country_code, rest_of_number) 

2669 

2670 # If this fails, they must be using a strange country calling code 

2671 # that we don't recognize, or that doesn't exist. 

2672 raise NumberParseException(NumberParseException.INVALID_COUNTRY_CODE, 

2673 "Country calling code supplied was not recognised.") 

2674 elif metadata is not None: 

2675 # Check to see if the number starts with the country calling code for 

2676 # the default region. If so, we remove the country calling code, and 

2677 # do some checks on the validity of the number before and after. 

2678 default_country_code = metadata.country_code 

2679 default_country_code_str = str(metadata.country_code) 

2680 normalized_number = full_number 

2681 if normalized_number.startswith(default_country_code_str): 

2682 potential_national_number = full_number[len(default_country_code_str):] 

2683 general_desc = metadata.general_desc 

2684 _, potential_national_number, _ = _maybe_strip_national_prefix_carrier_code(potential_national_number, 

2685 metadata) 

2686 

2687 # If the number was not valid before but is valid now, or if it 

2688 # was too long before, we consider the number with the country 

2689 # calling code stripped to be a better result and keep that 

2690 # instead. 

2691 if ((not _match_national_number(full_number, general_desc, False) and 

2692 _match_national_number(potential_national_number, general_desc, False)) or 

2693 (_test_number_length(full_number, metadata) == ValidationResult.TOO_LONG)): 

2694 if keep_raw_input: 

2695 numobj.country_code_source = CountryCodeSource.FROM_NUMBER_WITHOUT_PLUS_SIGN 

2696 numobj.country_code = default_country_code 

2697 return (default_country_code, potential_national_number) 

2698 

2699 # No country calling code present. 

2700 numobj.country_code = 0 

2701 return (0, U_EMPTY_STRING) 

2702 

2703 

2704def _parse_prefix_as_idd(idd_pattern, number): 

2705 """Strips the IDD from the start of the number if present. 

2706 

2707 Helper function used by _maybe_strip_i18n_prefix_and_normalize(). 

2708 

2709 Returns a 2-tuple: 

2710 - Boolean indicating if IDD was stripped 

2711 - Number with IDD stripped 

2712 """ 

2713 match = idd_pattern.match(number) 

2714 if match: 

2715 match_end = match.end() 

2716 # Only strip this if the first digit after the match is not a 0, since 

2717 # country calling codes cannot begin with 0. 

2718 digit_match = _CAPTURING_DIGIT_PATTERN.search(number[match_end:]) 

2719 if digit_match: 

2720 normalized_group = normalize_digits_only(digit_match.group(1)) 

2721 if normalized_group == U_ZERO: 

2722 return (False, number) 

2723 return (True, number[match_end:]) 

2724 return (False, number) 

2725 

2726 

2727def _maybe_strip_i18n_prefix_and_normalize(number, possible_idd_prefix): 

2728 """Strips any international prefix (such as +, 00, 011) present in the 

2729 number provided, normalizes the resulting number, and indicates if an 

2730 international prefix was present. 

2731 

2732 Arguments: 

2733 number -- The non-normalized telephone number that we wish to strip any international 

2734 dialing prefix from. 

2735 possible_idd_prefix -- The international direct dialing prefix from the region we 

2736 think this number may be dialed in. 

2737 

2738 Returns a 2-tuple containing: 

2739 - The corresponding CountryCodeSource if an international dialing prefix 

2740 could be removed from the number, otherwise 

2741 CountryCodeSource.FROM_DEFAULT_COUNTRY if the number did not seem to 

2742 be in international format. 

2743 - The number with the prefix stripped. 

2744 """ 

2745 if len(number) == 0: 

2746 return (CountryCodeSource.FROM_DEFAULT_COUNTRY, number) 

2747 # Check to see if the number begins with one or more plus signs. 

2748 m = _PLUS_CHARS_PATTERN.match(number) 

2749 if m: 

2750 number = number[m.end():] 

2751 # Can now normalize the rest of the number since we've consumed the 

2752 # "+" sign at the start. 

2753 return (CountryCodeSource.FROM_NUMBER_WITH_PLUS_SIGN, 

2754 _normalize(number)) 

2755 

2756 # Attempt to parse the first digits as an international prefix. 

2757 idd_pattern = re_compile(possible_idd_prefix) 

2758 number = _normalize(number) 

2759 stripped, number = _parse_prefix_as_idd(idd_pattern, number) 

2760 if stripped: 

2761 return (CountryCodeSource.FROM_NUMBER_WITH_IDD, number) 

2762 else: 

2763 return (CountryCodeSource.FROM_DEFAULT_COUNTRY, number) 

2764 

2765 

2766def _maybe_strip_national_prefix_carrier_code(number, metadata): 

2767 """Strips any national prefix (such as 0, 1) present in a number. 

2768 

2769 Arguments: 

2770 number -- The normalized telephone number that we wish to strip any 

2771 national dialing prefix from 

2772 metadata -- The metadata for the region that we think this number 

2773 is from. 

2774 

2775 Returns a 3-tuple of 

2776 - The carrier code extracted if it is present, otherwise an empty string. 

2777 - The number with the prefix stripped. 

2778 - Boolean indicating if a national prefix or carrier code (or both) could be extracted. 

2779 """ 

2780 carrier_code = U_EMPTY_STRING 

2781 possible_national_prefix = metadata.national_prefix_for_parsing 

2782 if (len(number) == 0 or 

2783 possible_national_prefix is None or 

2784 len(possible_national_prefix) == 0): 

2785 # Early return for numbers of zero length. 

2786 return (U_EMPTY_STRING, number, False) 

2787 

2788 # Attempt to parse the first digits as a national prefix. 

2789 prefix_pattern = re_compile(possible_national_prefix) 

2790 prefix_match = prefix_pattern.match(number) 

2791 if prefix_match: 

2792 general_desc = metadata.general_desc 

2793 # Check if the original number is viable. 

2794 is_viable_original_number = _match_national_number(number, general_desc, False) 

2795 # prefix_match.groups() == () implies nothing was captured by the 

2796 # capturing groups in possible_national_prefix; therefore, no 

2797 # transformation is necessary, and we just remove the national prefix. 

2798 num_groups = len(prefix_match.groups()) 

2799 transform_rule = metadata.national_prefix_transform_rule 

2800 if (transform_rule is None or 

2801 len(transform_rule) == 0 or 

2802 prefix_match.groups()[num_groups - 1] is None): 

2803 # If the original number was viable, and the resultant number is not, we return. 

2804 # Check that the resultant number is viable. If not, return. 

2805 national_number_match = _match_national_number(number[prefix_match.end():], general_desc, False) 

2806 if (is_viable_original_number and not national_number_match): 

2807 return (U_EMPTY_STRING, number, False) 

2808 

2809 if (num_groups > 0 and 

2810 prefix_match.groups(num_groups) is not None): 

2811 carrier_code = prefix_match.group(1) 

2812 return (carrier_code, number[prefix_match.end():], True) 

2813 else: 

2814 # Check that the resultant number is still viable. If not, 

2815 # return. Check this by copying the number and making the 

2816 # transformation on the copy first. 

2817 transformed_number = re.sub(prefix_pattern, transform_rule, number, count=1) 

2818 national_number_match = _match_national_number(transformed_number, general_desc, False) 

2819 if (is_viable_original_number and not national_number_match): 

2820 return ("", number, False) 

2821 if num_groups > 1: 

2822 carrier_code = prefix_match.group(1) 

2823 return (carrier_code, transformed_number, True) 

2824 else: 

2825 return (carrier_code, number, False) 

2826 

2827 

2828def _maybe_strip_extension(number): 

2829 """Strip extension from the end of a number string. 

2830 

2831 Strips any extension (as in, the part of the number dialled after the 

2832 call is connected, usually indicated with extn, ext, x or similar) from 

2833 the end of the number, and returns it. 

2834 

2835 Arguments: 

2836 number -- the non-normalized telephone number that we wish to strip the extension from. 

2837 

2838 Returns a 2-tuple of: 

2839 - the phone extension (or "" or not present) 

2840 - the number before the extension. 

2841 """ 

2842 match = _EXTN_PATTERN.search(number) 

2843 # If we find a potential extension, and the number preceding this is a 

2844 # viable number, we assume it is an extension. 

2845 if match and _is_viable_phone_number(number[:match.start()]): 

2846 # The numbers are captured into groups in the regular expression. 

2847 for group in match.groups(): 

2848 # We go through the capturing groups until we find one that 

2849 # captured some digits. If none did, then we will return the empty 

2850 # string. 

2851 if group is not None: 

2852 return (group, number[:match.start()]) 

2853 return ("", number) 

2854 

2855 

2856def _check_region_for_parsing(number, default_region): 

2857 """Checks to see that the region code used is valid, or if it is not 

2858 valid, that the number to parse starts with a + symbol so that we can 

2859 attempt to infer the region from the number. Returns False if it cannot 

2860 use the region provided and the region cannot be inferred. 

2861 """ 

2862 if not _is_valid_region_code(default_region): 

2863 # If the number is None or empty, we can't infer the region. 

2864 if number is None or len(number) == 0: 

2865 return False 

2866 match = _PLUS_CHARS_PATTERN.match(number) 

2867 if match is None: 

2868 return False 

2869 return True 

2870 

2871 

2872def _set_italian_leading_zeros_for_phone_number(national_number, numobj): 

2873 """A helper function to set the values related to leading zeros in a 

2874 PhoneNumber.""" 

2875 if len(national_number) > 1 and national_number[0] == U_ZERO: 

2876 numobj.italian_leading_zero = True 

2877 number_of_leading_zeros = 1 

2878 # Note that if the number is all "0"s, the last "0" is not counted as 

2879 # a leading zero. 

2880 while (number_of_leading_zeros < len(national_number) - 1 and 

2881 national_number[number_of_leading_zeros] == U_ZERO): 

2882 number_of_leading_zeros += 1 

2883 if number_of_leading_zeros != 1: 

2884 numobj.number_of_leading_zeros = number_of_leading_zeros 

2885 

2886 

2887def parse(number, region=None, keep_raw_input=False, 

2888 numobj=None, _check_region=True): 

2889 """Parse a string and return a corresponding PhoneNumber object. 

2890 

2891 The method is quite lenient and looks for a number in the input text 

2892 (raw input) and does not check whether the string is definitely only a 

2893 phone number. To do this, it ignores punctuation and white-space, as 

2894 well as any text before the number (e.g. a leading "Tel: ") and trims 

2895 the non-number bits. It will accept a number in any format (E164, 

2896 national, international etc), assuming it can be interpreted with the 

2897 defaultRegion supplied. It also attempts to convert any alpha characters 

2898 into digits if it thinks this is a vanity number of the type "1800 

2899 MICROSOFT". 

2900 

2901 This method will throw a NumberParseException if the number is not 

2902 considered to be a possible number. Note that validation of whether the 

2903 number is actually a valid number for a particular region is not 

2904 performed. This can be done separately with is_valid_number. 

2905 

2906 Note this method canonicalizes the phone number such that different 

2907 representations can be easily compared, no matter what form it was 

2908 originally entered in (e.g. national, international). If you want to 

2909 record context about the number being parsed, such as the raw input that 

2910 was entered, how the country code was derived etc. then ensure 

2911 keep_raw_input is set. 

2912 

2913 Note if any new field is added to this method that should always be filled 

2914 in, even when keep_raw_input is False, it should also be handled in the 

2915 _copy_core_fields_only() function. 

2916 

2917 Arguments: 

2918 number -- The number that we are attempting to parse. This can 

2919 contain formatting such as +, ( and -, as well as a phone 

2920 number extension. It can also be provided in RFC3966 format. 

2921 region -- The region that we are expecting the number to be from. This 

2922 is only used if the number being parsed is not written in 

2923 international format. The country_code for the number in 

2924 this case would be stored as that of the default region 

2925 supplied. If the number is guaranteed to start with a '+' 

2926 followed by the country calling code, then None or 

2927 UNKNOWN_REGION can be supplied. 

2928 keep_raw_input -- Whether to populate the raw_input field of the 

2929 PhoneNumber object with number (as well as the 

2930 country_code_source field). 

2931 numobj -- An optional existing PhoneNumber object to receive the 

2932 parsing results 

2933 _check_region -- Whether to check the supplied region parameter; 

2934 should always be True for external callers. 

2935 

2936 Returns a PhoneNumber object filled with the parse number. 

2937 

2938 Raises: 

2939 NumberParseException if the string is not considered to be a viable 

2940 phone number (e.g. too few or too many digits) or if no default 

2941 region was supplied and the number is not in international format 

2942 (does not start with +). 

2943 

2944 """ 

2945 if numobj is None: 

2946 numobj = PhoneNumber() 

2947 if number is None: 

2948 raise NumberParseException(NumberParseException.NOT_A_NUMBER, 

2949 "The phone number supplied was None.") 

2950 elif len(number) > _MAX_INPUT_STRING_LENGTH: 

2951 raise NumberParseException(NumberParseException.TOO_LONG, 

2952 "The string supplied was too long to parse.") 

2953 

2954 national_number = _build_national_number_for_parsing(number) 

2955 

2956 if not _is_viable_phone_number(national_number): 

2957 raise NumberParseException(NumberParseException.NOT_A_NUMBER, 

2958 "The string supplied did not seem to be a phone number.") 

2959 

2960 # Check the region supplied is valid, or that the extracted number starts 

2961 # with some sort of + sign so the number's region can be determined. 

2962 if _check_region and not _check_region_for_parsing(national_number, region): 

2963 raise NumberParseException(NumberParseException.INVALID_COUNTRY_CODE, 

2964 "Missing or invalid default region.") 

2965 if keep_raw_input: 

2966 numobj.raw_input = number 

2967 

2968 # Attempt to parse extension first, since it doesn't require 

2969 # region-specific data and we want to have the non-normalised number here. 

2970 extension, national_number = _maybe_strip_extension(national_number) 

2971 if len(extension) > 0: 

2972 numobj.extension = extension 

2973 if region is None: 

2974 metadata = None 

2975 else: 

2976 metadata = PhoneMetadata.metadata_for_region(region.upper(), None) 

2977 

2978 country_code = 0 

2979 try: 

2980 country_code, normalized_national_number = _maybe_extract_country_code(national_number, 

2981 metadata, 

2982 keep_raw_input, 

2983 numobj) 

2984 except NumberParseException: 

2985 _, e, _ = sys.exc_info() 

2986 matchobj = _PLUS_CHARS_PATTERN.match(national_number) 

2987 if (e.error_type == NumberParseException.INVALID_COUNTRY_CODE and 

2988 matchobj is not None): 

2989 # Strip the plus-char, and try again. 

2990 country_code, normalized_national_number = _maybe_extract_country_code(national_number[matchobj.end():], 

2991 metadata, 

2992 keep_raw_input, 

2993 numobj) 

2994 if country_code == 0: 

2995 raise NumberParseException(NumberParseException.INVALID_COUNTRY_CODE, 

2996 "Could not interpret numbers after plus-sign.") 

2997 else: 

2998 raise 

2999 

3000 if country_code != 0: 

3001 number_region = region_code_for_country_code(country_code) 

3002 if number_region != region: 

3003 # Metadata cannot be None because the country calling code is valid. 

3004 metadata = PhoneMetadata.metadata_for_region_or_calling_code(country_code, number_region) 

3005 assert metadata is not None 

3006 else: 

3007 # If no extracted country calling code, use the region supplied 

3008 # instead. The national number is just the normalized version of the 

3009 # number we were given to parse. 

3010 normalized_national_number += _normalize(national_number) 

3011 if region is not None: 

3012 country_code = metadata.country_code 

3013 numobj.country_code = country_code 

3014 elif keep_raw_input: 

3015 numobj.country_code_source = CountryCodeSource.UNSPECIFIED 

3016 

3017 if len(normalized_national_number) < _MIN_LENGTH_FOR_NSN: 

3018 raise NumberParseException(NumberParseException.TOO_SHORT_NSN, 

3019 "The string supplied is too short to be a phone number.") 

3020 if metadata is not None: 

3021 potential_national_number = normalized_national_number 

3022 carrier_code, potential_national_number, _ = _maybe_strip_national_prefix_carrier_code(potential_national_number, 

3023 metadata) 

3024 # We require that the NSN remaining after stripping the national 

3025 # prefix and carrier code be long enough to be a possible length for 

3026 # the region. Otherwise, we don't do the stripping, since the original 

3027 # number could be a valid short number. 

3028 validation_result = _test_number_length(potential_national_number, metadata) 

3029 if validation_result not in (ValidationResult.TOO_SHORT, 

3030 ValidationResult.IS_POSSIBLE_LOCAL_ONLY, 

3031 ValidationResult.INVALID_LENGTH): 

3032 normalized_national_number = potential_national_number 

3033 if keep_raw_input and carrier_code is not None and len(carrier_code) > 0: 

3034 numobj.preferred_domestic_carrier_code = carrier_code 

3035 len_national_number = len(normalized_national_number) 

3036 if len_national_number < _MIN_LENGTH_FOR_NSN: # pragma no cover 

3037 # Check of _is_viable_phone_number() at the top of this function makes 

3038 # this effectively unhittable. 

3039 raise NumberParseException(NumberParseException.TOO_SHORT_NSN, 

3040 "The string supplied is too short to be a phone number.") 

3041 if len_national_number > _MAX_LENGTH_FOR_NSN: 

3042 raise NumberParseException(NumberParseException.TOO_LONG, 

3043 "The string supplied is too long to be a phone number.") 

3044 _set_italian_leading_zeros_for_phone_number(normalized_national_number, numobj) 

3045 numobj.national_number = to_long(normalized_national_number) 

3046 return numobj 

3047 

3048 

3049def _extract_phone_context(number_to_extract_from, index_of_phone_context): 

3050 """Extracts the value of the phone-context parameter of number_to_extract_from where the index of 

3051 ";phone-context=" is the parameter index_of_phone_context, following the syntax defined in 

3052 RFC3966. 

3053 

3054 Returns the extracted string (possibly empty), or None if no phone-context parameter is found.""" 

3055 # If no phone-context parameter is present 

3056 if index_of_phone_context == -1: 

3057 return None 

3058 

3059 phone_context_start = index_of_phone_context + len(_RFC3966_PHONE_CONTEXT) 

3060 # If phone-context parameter is empty 

3061 if phone_context_start >= len(number_to_extract_from): 

3062 return U_EMPTY_STRING 

3063 

3064 phone_context_end = number_to_extract_from.find(';', phone_context_start) 

3065 # If phone-context is not the last parameter 

3066 if phone_context_end != -1: 

3067 return number_to_extract_from[phone_context_start:phone_context_end] 

3068 else: 

3069 return number_to_extract_from[phone_context_start:] 

3070 

3071 

3072def _is_phone_context_valid(phone_context): 

3073 """"Returns whether the value of phoneContext follows the syntax defined in RFC3966.""" 

3074 if phone_context is None: 

3075 return True 

3076 if len(phone_context) == 0: 

3077 return False 

3078 

3079 # Does phone-context value match pattern of global-number-digits or domainname 

3080 return (fullmatch(_RFC3966_GLOBAL_NUMBER_DIGITS_PATTERN, phone_context) or 

3081 fullmatch(_RFC3966_DOMAINNAME_PATTERN, phone_context)) 

3082 

3083 

3084def _build_national_number_for_parsing(number): 

3085 """Converts number to a form that we can parse and return it if it is 

3086 written in RFC3966; otherwise extract a possible number out of it and return it.""" 

3087 index_of_phone_context = number.find(_RFC3966_PHONE_CONTEXT) 

3088 

3089 phone_context = _extract_phone_context(number, index_of_phone_context) 

3090 if not _is_phone_context_valid(phone_context): 

3091 raise NumberParseException(NumberParseException.NOT_A_NUMBER, "The phone-context value is invalid") 

3092 if phone_context is not None: 

3093 # If the phone context contains a phone number prefix, we need to 

3094 # capture it, whereas domains will be ignored. 

3095 if phone_context[0] == _PLUS_SIGN: 

3096 # Additional parameters might follow the phone context. If so, we 

3097 # will remove them here because the parameters after phone context 

3098 # are not important for parsing the phone number. 

3099 national_number = phone_context 

3100 else: 

3101 national_number = U_EMPTY_STRING 

3102 

3103 # Now append everything between the "tel:" prefix and the 

3104 # phone-context. This should include the national number, an optional 

3105 # extension or isdn-subaddress component. Note we also handle the case 

3106 # when "tel:" is missing, as we have seen in some of the phone number 

3107 # inputs. In that case we append everything from the beginning. 

3108 index_of_rfc3996_prefix = number.find(_RFC3966_PREFIX) 

3109 index_of_national_number = ((index_of_rfc3996_prefix + len(_RFC3966_PREFIX)) 

3110 if (index_of_rfc3996_prefix >= 0) else 0) 

3111 national_number += number[index_of_national_number:index_of_phone_context] 

3112 else: 

3113 # Extract a possible number from the string passed in (this strips leading characters that 

3114 # could not be the start of a phone number.) 

3115 national_number = _extract_possible_number(number) 

3116 

3117 # Delete the isdn-subaddress and everything after it if it is 

3118 # present. Note extension won't appear at the same time with 

3119 # isdn-subaddress according to paragraph 5.3 of the RFC3966 spec, 

3120 index_of_isdn = national_number.find(_RFC3966_ISDN_SUBADDRESS) 

3121 if index_of_isdn > 0: 

3122 national_number = national_number[:index_of_isdn] 

3123 # If both phone context and isdn-subaddress are absent but other 

3124 # parameters are present, the parameters are left in national_number. This 

3125 # is because we are concerned about deleting content from a potential 

3126 # number string when there is no strong evidence that the number is 

3127 # actually written in RFC3966. 

3128 return national_number 

3129 

3130 

3131def _copy_core_fields_only(inobj): 

3132 """Returns a new phone number containing only the fields needed to uniquely 

3133 identify a phone number, rather than any fields that capture the context in 

3134 which the phone number was created. 

3135 """ 

3136 numobj = PhoneNumber() 

3137 numobj.country_code = inobj.country_code 

3138 numobj.national_number = inobj.national_number 

3139 if inobj.extension is not None and len(inobj.extension) > 0: 

3140 numobj.extension = inobj.extension 

3141 if inobj.italian_leading_zero: 

3142 numobj.italian_leading_zero = True 

3143 # This field is only relevant if there are leading zeros at all. 

3144 numobj.number_of_leading_zeros = inobj.number_of_leading_zeros 

3145 if numobj.number_of_leading_zeros is None: 

3146 # No number set is implicitly a count of 1; make it explicit. 

3147 numobj.number_of_leading_zeros = 1 

3148 return numobj 

3149 

3150 

3151def _is_number_match_OO(numobj1_in, numobj2_in): 

3152 """Takes two phone number objects and compares them for equality.""" 

3153 # We only care about the fields that uniquely define a number, so we copy these across explicitly. 

3154 numobj1 = _copy_core_fields_only(numobj1_in) 

3155 numobj2 = _copy_core_fields_only(numobj2_in) 

3156 

3157 # Early exit if both had extensions and these are different. 

3158 if (numobj1.extension is not None and 

3159 numobj2.extension is not None and 

3160 numobj1.extension != numobj2.extension): 

3161 return MatchType.NO_MATCH 

3162 

3163 country_code1 = numobj1.country_code 

3164 country_code2 = numobj2.country_code 

3165 # Both had country_code specified. 

3166 if country_code1 != 0 and country_code2 != 0: 

3167 if numobj1 == numobj2: 

3168 return MatchType.EXACT_MATCH 

3169 elif (country_code1 == country_code2 and 

3170 _is_national_number_suffix_of_other(numobj1, numobj2)): 

3171 # A SHORT_NSN_MATCH occurs if there is a difference because of the 

3172 # presence or absence of an 'Italian leading zero', the presence 

3173 # or absence of an extension, or one NSN being a shorter variant 

3174 # of the other. 

3175 return MatchType.SHORT_NSN_MATCH 

3176 # This is not a match. 

3177 return MatchType.NO_MATCH 

3178 

3179 # Checks cases where one or both country_code fields were not 

3180 # specified. To make equality checks easier, we first set the country_code 

3181 # fields to be equal. 

3182 numobj1.country_code = country_code2 

3183 # If all else was the same, then this is an NSN_MATCH. 

3184 if numobj1 == numobj2: 

3185 return MatchType.NSN_MATCH 

3186 if _is_national_number_suffix_of_other(numobj1, numobj2): 

3187 return MatchType.SHORT_NSN_MATCH 

3188 return MatchType.NO_MATCH 

3189 

3190 

3191def _is_national_number_suffix_of_other(numobj1, numobj2): 

3192 """Returns true when one national number is the suffix of the other or both 

3193 are the same. 

3194 """ 

3195 nn1 = str(numobj1.national_number) 

3196 nn2 = str(numobj2.national_number) 

3197 # Note that endswith returns True if the numbers are equal. 

3198 return nn1.endswith(nn2) or nn2.endswith(nn1) 

3199 

3200 

3201def _is_number_match_SS(number1, number2): 

3202 """Takes two phone numbers as strings and compares them for equality. 

3203 

3204 This is a convenience wrapper for _is_number_match_OO/_is_number_match_OS. 

3205 No default region is known. 

3206 """ 

3207 try: 

3208 numobj1 = parse(number1, UNKNOWN_REGION) 

3209 return _is_number_match_OS(numobj1, number2) 

3210 except NumberParseException: 

3211 _, exc, _ = sys.exc_info() 

3212 if exc.error_type == NumberParseException.INVALID_COUNTRY_CODE: 

3213 try: 

3214 numobj2 = parse(number2, UNKNOWN_REGION) 

3215 return _is_number_match_OS(numobj2, number1) 

3216 except NumberParseException: 

3217 _, exc2, _ = sys.exc_info() 

3218 if exc2.error_type == NumberParseException.INVALID_COUNTRY_CODE: 

3219 try: 

3220 numobj1 = parse(number1, None, keep_raw_input=False, 

3221 _check_region=False, numobj=None) 

3222 numobj2 = parse(number2, None, keep_raw_input=False, 

3223 _check_region=False, numobj=None) 

3224 return _is_number_match_OO(numobj1, numobj2) 

3225 except NumberParseException: 

3226 return MatchType.NOT_A_NUMBER 

3227 

3228 # One or more of the phone numbers we are trying to match is not a viable 

3229 # phone number. 

3230 return MatchType.NOT_A_NUMBER 

3231 

3232 

3233def _is_number_match_OS(numobj1, number2): 

3234 """Wrapper variant of _is_number_match_OO that copes with one 

3235 PhoneNumber object and one string.""" 

3236 # First see if the second number has an implicit country calling code, by 

3237 # attempting to parse it. 

3238 try: 

3239 numobj2 = parse(number2, UNKNOWN_REGION) 

3240 return _is_number_match_OO(numobj1, numobj2) 

3241 except NumberParseException: 

3242 _, exc, _ = sys.exc_info() 

3243 if exc.error_type == NumberParseException.INVALID_COUNTRY_CODE: 

3244 # The second number has no country calling code. EXACT_MATCH is no 

3245 # longer possible. We parse it as if the region was the same as 

3246 # that for the first number, and if EXACT_MATCH is returned, we 

3247 # replace this with NSN_MATCH. 

3248 region1 = region_code_for_country_code(numobj1.country_code) 

3249 try: 

3250 if region1 != UNKNOWN_REGION: 

3251 numobj2 = parse(number2, region1) 

3252 match = _is_number_match_OO(numobj1, numobj2) 

3253 if match == MatchType.EXACT_MATCH: 

3254 return MatchType.NSN_MATCH 

3255 else: 

3256 return match 

3257 else: 

3258 # If the first number didn't have a valid country calling 

3259 # code, then we parse the second number without one as 

3260 # well. 

3261 numobj2 = parse(number2, None, keep_raw_input=False, 

3262 _check_region=False, numobj=None) 

3263 return _is_number_match_OO(numobj1, numobj2) 

3264 except NumberParseException: 

3265 return MatchType.NOT_A_NUMBER 

3266 # One or more of the phone numbers we are trying to match is not a viable 

3267 # phone number. 

3268 return MatchType.NOT_A_NUMBER 

3269 

3270 

3271def is_number_match(num1, num2): 

3272 """Takes two phone numbers and compares them for equality. 

3273 

3274 For example, the numbers +1 345 657 1234 and 657 1234 are a SHORT_NSN_MATCH. 

3275 The numbers +1 345 657 1234 and 345 657 are a NO_MATCH. 

3276 

3277 Arguments 

3278 num1 -- First number object or string to compare. Can contain formatting, 

3279 and can have country calling code specified with + at the start. 

3280 num2 -- Second number object or string to compare. Can contain formatting, 

3281 and can have country calling code specified with + at the start. 

3282 

3283 Returns: 

3284 - EXACT_MATCH if the country_code, NSN, presence of a leading zero for 

3285 Italian numbers and any extension present are the same. 

3286 - NSN_MATCH if either or both has no region specified, and the NSNs and 

3287 extensions are the same. 

3288 - SHORT_NSN_MATCH if either or both has no region specified, or the 

3289 region specified is the same, and one NSN could be a shorter version of 

3290 the other number. This includes the case where one has an extension 

3291 specified, and the other does not. 

3292 - NO_MATCH otherwise. 

3293 """ 

3294 if isinstance(num1, PhoneNumber) and isinstance(num2, PhoneNumber): 

3295 return _is_number_match_OO(num1, num2) 

3296 elif isinstance(num1, PhoneNumber): 

3297 return _is_number_match_OS(num1, num2) 

3298 elif isinstance(num2, PhoneNumber): 

3299 return _is_number_match_OS(num2, num1) 

3300 else: 

3301 return _is_number_match_SS(num1, num2) 

3302 

3303 

3304def can_be_internationally_dialled(numobj): 

3305 """Returns True if the number can only be dialled from outside the region, 

3306 or unknown. 

3307 

3308 If the number can only be dialled from within the region 

3309 as well, returns False. Does not check the number is a valid number. 

3310 Note that, at the moment, this method does not handle short numbers (which 

3311 are currently all presumed to not be diallable from outside their country). 

3312 

3313 Arguments: 

3314 numobj -- the phone number objectfor which we want to know whether it is 

3315 diallable from outside the region. 

3316 """ 

3317 metadata = PhoneMetadata.metadata_for_region(region_code_for_number(numobj), None) 

3318 if metadata is None: 

3319 # Note numbers belonging to non-geographical entities (e.g. +800 

3320 # numbers) are always internationally diallable, and will be caught 

3321 # here. 

3322 return True 

3323 nsn = national_significant_number(numobj) 

3324 return not _is_number_matching_desc(nsn, metadata.no_international_dialling) 

3325 

3326 

3327def is_mobile_number_portable_region(region_code): 

3328 """Returns true if the supplied region supports mobile number portability. 

3329 Returns false for invalid, unknown or regions that don't support mobile 

3330 number portability. 

3331 

3332 Arguments: 

3333 region_code -- the region for which we want to know whether it supports mobile number 

3334 portability or not. 

3335 """ 

3336 metadata = PhoneMetadata.metadata_for_region(region_code, None) 

3337 if metadata is None: 

3338 return False 

3339 return metadata.mobile_number_portable_region 

3340 

3341 

3342class NumberParseException(UnicodeMixin, Exception): 

3343 """Exception when attempting to parse a putative phone number""" 

3344 

3345 # The reason a string could not be interpreted as a phone number. 

3346 

3347 # The country code supplied did not belong to a supported country or 

3348 # non-geographical entity. 

3349 INVALID_COUNTRY_CODE = 0 

3350 

3351 # This generally indicates the string passed in had fewer than 3 digits in 

3352 # it. The number failed to match the regular expression 

3353 # _VALID_PHONE_NUMBER in phonenumberutil.py. 

3354 

3355 # This indicates the string passed is not a valid number. Either the string 

3356 # had less than 3 digits in it or had an invalid phone-context 

3357 # parameter. More specifically, the number failed to match the regular 

3358 # expression _VALID_PHONE_NUMBER, )RFC3966_GLOBAL_NUMBER_DIGITS, or 

3359 # _RFC3966_DOMAINNAME in phonenumberutil.py. 

3360 NOT_A_NUMBER = 1 

3361 

3362 # This indicates the string started with an international dialing prefix, 

3363 # but after this was removed, it had fewer digits than any valid phone 

3364 # number (including country code) could have. 

3365 TOO_SHORT_AFTER_IDD = 2 

3366 

3367 # This indicates the string, after any country code has been stripped, 

3368 # had fewer digits than any valid phone number could have. 

3369 TOO_SHORT_NSN = 3 

3370 

3371 # This indicates the string had more digits than any valid phone number 

3372 # could have 

3373 TOO_LONG = 4 

3374 

3375 def __init__(self, error_type, msg): 

3376 Exception.__init__(self, msg) 

3377 self.error_type = error_type 

3378 self._msg = msg 

3379 

3380 def __reduce__(self): 

3381 return (type(self), (self.error_type, self._msg)) 

3382 

3383 def __unicode__(self): 

3384 return unicod("(%s) %s") % (self.error_type, self._msg) 

3385 

3386 

3387def _match_national_number(number, number_desc, allow_prefix_match): 

3388 """Returns whether the given national number (a string containing only decimal digits) matches 

3389 the national number pattern defined in the given PhoneNumberDesc object. 

3390 """ 

3391 # We don't want to consider it a prefix match when matching non-empty input against an empty 

3392 # pattern. 

3393 if number_desc is None or number_desc.national_number_pattern is None or len(number_desc.national_number_pattern) == 0: 

3394 return False 

3395 return _match(number, re_compile(number_desc.national_number_pattern), allow_prefix_match) 

3396 

3397 

3398def _match(number, pattern, allow_prefix_match): 

3399 if not pattern.match(number): 

3400 return False 

3401 else: 

3402 if fullmatch(pattern, number): 

3403 return True 

3404 else: 

3405 return allow_prefix_match