Skip to content

Commit 319c33e

Browse files
committed
Remove runtime use of u()
u() is slower than unicod(), and u() is only needed for string literals with \uXX escapes in them. Therefore use unicod() wherever possible, and make explicit strings used at runtime into constants.
1 parent 0fd60a0 commit 319c33e

7 files changed

Lines changed: 117 additions & 102 deletions

File tree

python/phonenumbers/asyoutypeformatter.py

Lines changed: 10 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@
2626
# limitations under the License.
2727
import re
2828

29-
from .util import u
29+
from .util import u, unicod, U_EMPTY_STRING
3030
from .unicode_util import digit as unicode_digit
3131
from .re_util import fullmatch
3232
from .phonemetadata import PhoneMetadata
@@ -35,26 +35,28 @@
3535
from .phonenumberutil import _extract_country_code, region_code_for_country_code
3636
from .phonenumberutil import country_code_for_region
3737

38-
_EMPTY_METADATA = PhoneMetadata(id=u(""), international_prefix=u("NA"), register=False)
38+
_EMPTY_METADATA = PhoneMetadata(id=unicod(""),
39+
international_prefix=unicod("NA"),
40+
register=False)
3941

4042
# A pattern that is used to match character classes in regular expressions. An
4143
# example of a character class is [1-4].
42-
_CHARACTER_CLASS_PATTERN = re.compile(u("\\[([^\\[\\]])*\\]"))
44+
_CHARACTER_CLASS_PATTERN = re.compile(unicod("\\[([^\\[\\]])*\\]"))
4345
# Any digit in a regular expression that actually denotes a digit. For
4446
# example, in the regular expression 80[0-2]\d{6,10}, the first 2 digits (8
4547
# and 0) are standalone digits, but the rest are not.
4648
# Two look-aheads are needed because the number following \\d could be a
4749
# two-digit number, since the phone number can be as long as 15 digits.
48-
_STANDALONE_DIGIT_PATTERN = re.compile(u("\\d(?=[^,}][^,}])"))
50+
_STANDALONE_DIGIT_PATTERN = re.compile(unicod("\\d(?=[^,}][^,}])"))
4951

5052
# A pattern that is used to determine if a number_format under
5153
# available_formats is eligible to be used by the AYTF. It is eligible when
5254
# the format element under number_format contains groups of the dollar sign
5355
# followed by a single digit, separated by valid phone number
5456
# punctuation. This prevents invalid punctuation (such as the star sign in
5557
# Israeli star numbers) getting into the output of the AYTF.
56-
_ELIGIBLE_FORMAT_PATTERN = re.compile(u("[") + _VALID_PUNCTUATION + u("]*") +
57-
u("(\\\\\\d") + u("[") + _VALID_PUNCTUATION + u("]*)+"))
58+
_ELIGIBLE_FORMAT_PATTERN = re.compile(unicod("[") + _VALID_PUNCTUATION + unicod("]*") +
59+
unicod("(\\\\\\d") + unicod("[") + _VALID_PUNCTUATION + unicod("]*)+"))
5860

5961
# This is the minimum length of national number accrued that is required to
6062
# trigger the formatter. The first element of the leading_digits_pattern of each
@@ -185,7 +187,7 @@ def _get_formatting_template(self, number_pattern, number_format):
185187
# entered so far is longer than the maximum the current formatting
186188
# rule can accommodate.
187189
if len(a_phone_number) < len(self._national_number):
188-
return u("")
190+
return U_EMPTY_STRING
189191
# Formats the number according to number_format
190192
template = re.sub(number_pattern, number_format, a_phone_number)
191193
# Replaces each digit with character _DIGIT_PLACEHOLDER
@@ -494,7 +496,7 @@ def _normalize_and_accrue_digits_and_plus_sign(self, next_char, remember_positio
494496
else:
495497
next_digit = unicode_digit(next_char, -1)
496498
if next_digit != -1:
497-
normalized_char = u(next_digit)
499+
normalized_char = unicod(next_digit)
498500
else: # pragma no cover
499501
normalized_char = next_char
500502
self._accrued_input_without_formatting += normalized_char

python/phonenumbers/geocoder.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,7 @@
4444
# See the License for the specific language governing permissions and
4545
# limitations under the License.
4646

47-
from .util import prnt, u
47+
from .util import prnt, U_EMPTY_STRING
4848
from .phonenumberutil import format_number, PhoneNumberFormat, is_valid_number
4949
from .phonenumberutil import region_code_for_number
5050

@@ -122,8 +122,8 @@ def area_description_for_number(numobj, lang, script=None, region=None):
122122
if name is not None:
123123
return name
124124
else:
125-
return u("")
126-
return u("")
125+
return U_EMPTY_STRING
126+
return U_EMPTY_STRING
127127

128128

129129
def country_name_for_number(numobj, lang, script=None, region=None):
@@ -156,7 +156,7 @@ def region_display_name(region_code, lang, script=None, region=None):
156156
other_lang = name[1:]
157157
name = LOCALE_DATA[region_code].get(other_lang, "")
158158
return name
159-
return u("")
159+
return U_EMPTY_STRING
160160

161161

162162
def description_for_valid_number(numobj, lang, script=None, region=None):

python/phonenumbers/phonemetadata.py

Lines changed: 41 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -124,17 +124,17 @@ def __repr__(self):
124124
def __unicode__(self):
125125
# Generate a string that is valid Python input for the constructor.
126126
# Note that we use rpr (variant of repr), which generates its own quotes.
127-
result = u("NumberFormat(pattern=%s, format=%s") % (rpr(self.pattern), rpr(self.format))
127+
result = unicod("NumberFormat(pattern=%s, format=%s") % (rpr(self.pattern), rpr(self.format))
128128
if len(self.leading_digits_pattern) > 0:
129-
result += (u(", leading_digits_pattern=[%s]") %
130-
", ".join([rpr(ld) for ld in self.leading_digits_pattern]))
129+
result += (unicod(", leading_digits_pattern=[%s]") %
130+
unicod(", ").join([rpr(ld) for ld in self.leading_digits_pattern]))
131131
if self.national_prefix_formatting_rule is not None:
132-
result += u(", national_prefix_formatting_rule=%s") % rpr(self.national_prefix_formatting_rule)
132+
result += unicod(", national_prefix_formatting_rule=%s") % rpr(self.national_prefix_formatting_rule)
133133
if self.national_prefix_optional_when_formatting:
134-
result += u(", national_prefix_optional_when_formatting=%s") % str(self.national_prefix_optional_when_formatting)
134+
result += unicod(", national_prefix_optional_when_formatting=%s") % str(self.national_prefix_optional_when_formatting)
135135
if self.domestic_carrier_code_formatting_rule is not None:
136-
result += u(", domestic_carrier_code_formatting_rule=%s") % rpr(self.domestic_carrier_code_formatting_rule)
137-
result += u(")")
136+
result += unicod(", domestic_carrier_code_formatting_rule=%s") % rpr(self.domestic_carrier_code_formatting_rule)
137+
result += unicod(")")
138138
return result
139139

140140

@@ -185,18 +185,18 @@ def __repr__(self):
185185

186186
def __unicode__(self):
187187
# Generate a string that is valid Python input for constructor
188-
result = u("PhoneNumberDesc(")
189-
sep = u("")
188+
result = unicod("PhoneNumberDesc(")
189+
sep = unicod("")
190190
if self.national_number_pattern is not None:
191-
result += u("%snational_number_pattern=%s") % (sep, rpr(self.national_number_pattern))
192-
sep = u(", ")
191+
result += unicod("%snational_number_pattern=%s") % (sep, rpr(self.national_number_pattern))
192+
sep = unicod(", ")
193193
if self.possible_number_pattern is not None:
194-
result += u("%spossible_number_pattern=%s") % (sep, rpr(self.possible_number_pattern))
195-
sep = u(", ")
194+
result += unicod("%spossible_number_pattern=%s") % (sep, rpr(self.possible_number_pattern))
195+
sep = unicod(", ")
196196
if self.example_number is not None:
197-
result += u("%sexample_number=%s") % (sep, rpr(self.example_number))
198-
sep = u(", ")
199-
result += u(")")
197+
result += unicod("%sexample_number=%s") % (sep, rpr(self.example_number))
198+
sep = unicod(", ")
199+
result += unicod(")")
200200
return result
201201

202202

@@ -416,42 +416,42 @@ def __unicode__(self):
416416
country_code = self.country_code
417417
if country_code is None:
418418
country_code = -1
419-
result = (u("PhoneMetadata(id='%s', country_code=%d, international_prefix=%s") %
419+
result = (unicod("PhoneMetadata(id='%s', country_code=%d, international_prefix=%s") %
420420
(self.id, country_code, rpr(self.international_prefix)))
421-
result += ",\n general_desc=%s" % self.general_desc
422-
result += ",\n fixed_line=%s" % self.fixed_line
423-
result += ",\n mobile=%s" % self.mobile
424-
result += ",\n toll_free=%s" % self.toll_free
425-
result += ",\n premium_rate=%s" % self.premium_rate
426-
result += ",\n shared_cost=%s" % self.shared_cost
427-
result += ",\n personal_number=%s" % self.personal_number
428-
result += ",\n voip=%s" % self.voip
429-
result += ",\n pager=%s" % self.pager
430-
result += ",\n uan=%s" % self.uan
431-
result += ",\n emergency=%s" % self.emergency
432-
result += ",\n voicemail=%s" % self.voicemail
433-
result += ",\n no_international_dialling=%s" % self.no_international_dialling
421+
result += unicod(",\n general_desc=%s") % self.general_desc
422+
result += unicod(",\n fixed_line=%s") % self.fixed_line
423+
result += unicod(",\n mobile=%s") % self.mobile
424+
result += unicod(",\n toll_free=%s") % self.toll_free
425+
result += unicod(",\n premium_rate=%s") % self.premium_rate
426+
result += unicod(",\n shared_cost=%s") % self.shared_cost
427+
result += unicod(",\n personal_number=%s") % self.personal_number
428+
result += unicod(",\n voip=%s") % self.voip
429+
result += unicod(",\n pager=%s") % self.pager
430+
result += unicod(",\n uan=%s") % self.uan
431+
result += unicod(",\n emergency=%s") % self.emergency
432+
result += unicod(",\n voicemail=%s") % self.voicemail
433+
result += unicod(",\n no_international_dialling=%s") % self.no_international_dialling
434434

435435
if self.preferred_international_prefix is not None:
436-
result += ",\n preferred_international_prefix=%s" % rpr(self.preferred_international_prefix)
436+
result += unicod(",\n preferred_international_prefix=%s") % rpr(self.preferred_international_prefix)
437437
if self.national_prefix is not None:
438-
result += ",\n national_prefix=%s" % rpr(self.national_prefix)
438+
result += unicod(",\n national_prefix=%s") % rpr(self.national_prefix)
439439
if self.preferred_extn_prefix is not None:
440-
result += ",\n preferred_extn_prefix=%s" % rpr(self.preferred_extn_prefix)
440+
result += unicod(",\n preferred_extn_prefix=%s") % rpr(self.preferred_extn_prefix)
441441
if self.national_prefix_for_parsing is not None:
442-
result += ",\n national_prefix_for_parsing=%s" % rpr(self.national_prefix_for_parsing)
442+
result += unicod(",\n national_prefix_for_parsing=%s") % rpr(self.national_prefix_for_parsing)
443443
if self.national_prefix_transform_rule is not None:
444444
# Note that we use rpr() on self.national_prefix_transform_rule, which generates its own quotes
445-
result += ",\n national_prefix_transform_rule=%s" % rpr(self.national_prefix_transform_rule)
445+
result += unicod(",\n national_prefix_transform_rule=%s") % rpr(self.national_prefix_transform_rule)
446446
if len(self.number_format) > 0:
447-
result += ",\n number_format=[%s]" % ',\n '.join(map(u, self.number_format))
447+
result += unicod(",\n number_format=[%s]") % ',\n '.join(map(u, self.number_format))
448448
if len(self.intl_number_format) > 0:
449-
result += ",\n intl_number_format=[%s]" % ',\n '.join(map(u, self.intl_number_format))
449+
result += unicod(",\n intl_number_format=[%s]") % ',\n '.join(map(u, self.intl_number_format))
450450
if self.main_country_for_code:
451-
result += ",\n main_country_for_code=True"
451+
result += unicod(",\n main_country_for_code=True")
452452
if self.leading_digits is not None:
453-
result += ",\n leading_digits='%s'" % self.leading_digits
453+
result += unicod(",\n leading_digits='%s'") % self.leading_digits
454454
if self.leading_zero_possible:
455-
result += ",\n leading_zero_possible=True"
456-
result += u(")")
455+
result += unicod(",\n leading_zero_possible=True")
456+
result += unicod(")")
457457
return result

python/phonenumbers/phonenumber.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -186,7 +186,7 @@ def __ne__(self, other):
186186
return not self.__eq__(other)
187187

188188
def __repr__(self):
189-
return (("PhoneNumber(country_code=%s, national_number=%s, extension=%s, " +
189+
return (unicod("PhoneNumber(country_code=%s, national_number=%s, extension=%s, " +
190190
"italian_leading_zero=%s, country_code_source=%s, preferred_domestic_carrier_code=%s)") %
191191
(self.country_code,
192192
self.national_number,
@@ -196,16 +196,16 @@ def __repr__(self):
196196
rpr(self.preferred_domestic_carrier_code)))
197197

198198
def __unicode__(self):
199-
result = ("Country Code: %s National Number: %s" %
199+
result = (unicod("Country Code: %s National Number: %s") %
200200
(self.country_code, self.national_number))
201201
if self.italian_leading_zero is not None:
202-
result += " Leading Zero: %s" % self.italian_leading_zero
202+
result += unicod(" Leading Zero: %s") % self.italian_leading_zero
203203
if self.extension is not None:
204-
result += " Extension: %s" % self.extension
204+
result += unicod(" Extension: %s") % self.extension
205205
if self.country_code_source is not None:
206-
result += " Country Code Source: %s" % self.country_code_source
206+
result += unicod(" Country Code Source: %s") % self.country_code_source
207207
if self.preferred_domestic_carrier_code is not None:
208-
result += (" Preferred Domestic Carrier Code: %s" %
208+
result += (unicod(" Preferred Domestic Carrier Code: %s") %
209209
self.preferred_domestic_carrier_code)
210210
return result
211211

python/phonenumbers/phonenumbermatcher.py

Lines changed: 14 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,8 @@
2020

2121
# Extra regexp function; see README
2222
from .re_util import fullmatch
23-
from .util import UnicodeMixin, u
23+
from .util import UnicodeMixin, u, unicod
24+
from .util import U_EMPTY_STRING, U_DASH, U_SEMICOLON, U_SLASH, U_X_LOWER, U_X_UPPER
2425
from .unicode_util import Category, Block, is_letter
2526
from .phonenumberutil import _MAX_LENGTH_FOR_NSN, _MAX_LENGTH_COUNTRY_CODE
2627
from .phonenumberutil import _VALID_PUNCTUATION, _PLUS_CHARS, _NON_DIGITS_PATTERN
@@ -40,7 +41,7 @@ def _limit(lower, upper):
4041
"""Returns a regular expression quantifier with an upper and lower limit."""
4142
if ((lower < 0) or (upper <= 0) or (upper < lower)):
4243
raise Exception("Illegal argument to _limit")
43-
return u("{%d,%d}") % (lower, upper)
44+
return unicod("{%d,%d}") % (lower, upper)
4445

4546
# Build the MATCHING_BRACKETS and PATTERN regular expression patterns. The
4647
# building blocks below exist to make the patterns more easily understood.
@@ -210,7 +211,7 @@ def _verify_strict_grouping(numobj, candidate):
210211
# The check here makes sure that we haven't mistakenly already used the extension to
211212
# match the last group of the subscriber number. Note the extension cannot have
212213
# formatting in-between digits.
213-
return (normalized_candidate[from_index:].find(numobj.extension or "") != -1)
214+
return (normalized_candidate[from_index:].find(numobj.extension or U_EMPTY_STRING) != -1)
214215

215216

216217
def _verify_exact_grouping(numobj, candidate):
@@ -258,19 +259,19 @@ def _get_national_number_groups(numobj):
258259
rfc3966_format = format_number(numobj, PhoneNumberFormat.RFC3966)
259260
# We remove the extension part from the formatted string before splitting
260261
# it into different groups.
261-
end_index = rfc3966_format.find(u(";"))
262+
end_index = rfc3966_format.find(U_SEMICOLON)
262263
if end_index < 0:
263264
end_index = len(rfc3966_format)
264265

265266
# The country-code will have a '-' following it.
266-
start_index = rfc3966_format.find(u("-")) + 1
267-
return rfc3966_format[start_index:end_index].split(u("-"))
267+
start_index = rfc3966_format.find(U_DASH) + 1
268+
return rfc3966_format[start_index:end_index].split(U_DASH)
268269

269270

270271
def _contains_more_than_one_slash(candidate):
271-
first_slash_index = candidate.find(u("/"))
272+
first_slash_index = candidate.find(U_SLASH)
272273
return (first_slash_index > 0 and
273-
(candidate.find(u("/"), (first_slash_index + 1)) != -1))
274+
(candidate.find(U_SLASH, (first_slash_index + 1)) != -1))
274275

275276

276277
def _contains_only_valid_x_chars(numobj, candidate):
@@ -283,9 +284,9 @@ def _contains_only_valid_x_chars(numobj, candidate):
283284
# character of the string.
284285
ii = 0
285286
while ii < (len(candidate) - 1):
286-
if (candidate[ii] == 'x' or candidate[ii] == 'X'):
287+
if (candidate[ii] == U_X_LOWER or candidate[ii] == U_X_UPPER):
287288
next_char = candidate[ii + 1]
288-
if (next_char == 'x' or next_char == 'X'):
289+
if (next_char == U_X_LOWER or next_char == U_X_UPPER):
289290
# This is the carrier code case, in which the 'X's always
290291
# precede the national significant number.
291292
ii += 1
@@ -375,7 +376,7 @@ def __init__(self, text, region,
375376
# The text searched for phone numbers.
376377
self.text = text
377378
if self.text is None:
378-
self.text = u("")
379+
self.text = U_EMPTY_STRING
379380
# The region (country) to assume for phone numbers without an
380381
# international prefix, possibly None.
381382
self.preferred_region = region
@@ -661,10 +662,10 @@ def __ne__(self, other):
661662
return not self.__eq__(other)
662663

663664
def __repr__(self):
664-
return ("PhoneNumberMatch(start=%r, raw_string=%r, numobj=%r)" %
665+
return (unicod("PhoneNumberMatch(start=%r, raw_string=%r, numobj=%r)") %
665666
(self.start,
666667
self.raw_string,
667668
self.number))
668669

669670
def __unicode__(self):
670-
return u("PhoneNumberMatch [%s,%s) %s") % (self.start, self.end, self.raw_string)
671+
return unicod("PhoneNumberMatch [%s,%s) %s") % (self.start, self.end, self.raw_string)

0 commit comments

Comments
 (0)