Skip to content

Commit bcce85c

Browse files
gh-163115: Speed up urllib.parse.quote() and quote_plus() for ASCII str inputs
Bypass the bytes encoding and map(quoter, bs) loop for exact ASCII str inputs using str.rstrip() and str.translate(). Initialize default translation tables lazily, cache custom safe tables via lru_cache, and clear all of them in clear_cache().
1 parent 64c20ff commit bcce85c

3 files changed

Lines changed: 208 additions & 1 deletion

File tree

‎Lib/test/test_urlparse.py‎

Lines changed: 127 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1589,6 +1589,120 @@ def test_quote_errors(self):
15891589
self.assertRaises(TypeError, urllib.parse.quote, b'foo',
15901590
encoding='utf-8')
15911591
self.assertRaises(TypeError, urllib.parse.quote, b'foo', errors='strict')
1592+
self.assertRaises(TypeError, urllib.parse.quote, 'abc', errors=123)
1593+
self.assertRaises(TypeError, urllib.parse.quote_plus, 'abc', errors=123)
1594+
1595+
def test_quote_ascii_fastpath(self):
1596+
all_ascii = ''.join(chr(i) for i in range(128))
1597+
all_ascii_bytes = bytes(range(128))
1598+
1599+
# Verify quote() and quote_plus() match quote_from_bytes() across all
1600+
# 128 ASCII characters and custom safe values.
1601+
for safe in ('/', '', ' ', '+', ' /?=&', '~_-.'):
1602+
expected_quote = urllib.parse.quote_from_bytes(all_ascii_bytes, safe)
1603+
self.assertEqual(urllib.parse.quote(all_ascii, safe=safe),
1604+
expected_quote)
1605+
1606+
expected_plus = urllib.parse.quote_from_bytes(
1607+
all_ascii_bytes, safe + ' '
1608+
).replace(' ', '+')
1609+
self.assertEqual(urllib.parse.quote_plus(all_ascii, safe=safe),
1610+
expected_plus)
1611+
1612+
# Every individual ASCII char as safe
1613+
for i in range(128):
1614+
ch = chr(i)
1615+
expected = urllib.parse.quote_from_bytes(all_ascii_bytes, ch)
1616+
self.assertEqual(urllib.parse.quote(all_ascii, safe=ch), expected)
1617+
expected_plus = urllib.parse.quote_from_bytes(
1618+
all_ascii_bytes, ch + ' '
1619+
).replace(' ', '+')
1620+
self.assertEqual(urllib.parse.quote_plus(all_ascii, safe=ch),
1621+
expected_plus)
1622+
1623+
# safe=' ' in quote_plus still encodes spaces as '+'
1624+
self.assertEqual(urllib.parse.quote_plus('a b+c', safe=' '), 'a+b%2Bc')
1625+
self.assertEqual(urllib.parse.quote_plus('a b+c', safe='+'), 'a+b+c')
1626+
1627+
# Non-ASCII safe characters are ignored
1628+
self.assertEqual(urllib.parse.quote('a/b c', safe='é/'), 'a/b%20c')
1629+
self.assertEqual(urllib.parse.quote_plus('a/b c', safe='é/'), 'a/b+c')
1630+
1631+
# Non-ASCII string fallback
1632+
self.assertEqual(urllib.parse.quote('café /a'), 'caf%C3%A9%20/a')
1633+
self.assertEqual(urllib.parse.quote_plus('café /a'), 'caf%C3%A9+%2Fa')
1634+
1635+
# Encodings: ASCII-compatible and non-ASCII-compatible
1636+
for enc in (None, 'utf-8', 'ascii', 'latin-1'):
1637+
self.assertEqual(urllib.parse.quote('a b/c', encoding=enc),
1638+
'a%20b/c')
1639+
self.assertEqual(urllib.parse.quote_plus('a b/c', encoding=enc),
1640+
'a+b%2Fc')
1641+
self.assertEqual(
1642+
urllib.parse.quote('abc', encoding='utf-16'),
1643+
urllib.parse.quote_from_bytes('abc'.encode('utf-16'), '/'),
1644+
)
1645+
self.assertEqual(
1646+
urllib.parse.quote_plus('a b', encoding='utf-16'),
1647+
urllib.parse.quote_from_bytes('a b'.encode('utf-16'), ' ').replace(' ', '+'),
1648+
)
1649+
1650+
# bytes inputs and bytes safe
1651+
self.assertEqual(urllib.parse.quote(b'a b/c'), 'a%20b/c')
1652+
self.assertEqual(urllib.parse.quote('a b/c', safe=b'/'), 'a%20b/c')
1653+
self.assertEqual(urllib.parse.quote_plus(b'a b/c'), 'a+b%2Fc')
1654+
self.assertEqual(urllib.parse.quote_plus('a b/c', safe=b'/'), 'a+b/c')
1655+
1656+
def test_quote_str_subclass(self):
1657+
class PlainSubStr(str):
1658+
pass
1659+
1660+
# Empty str subclass is returned as-is; non-empty returns plain str.
1661+
empty = PlainSubStr('')
1662+
self.assertIs(urllib.parse.quote(empty), empty)
1663+
self.assertIs(urllib.parse.quote_plus(empty), empty)
1664+
1665+
for s in (PlainSubStr('abc'), PlainSubStr('a b/c')):
1666+
res_q = urllib.parse.quote(s)
1667+
self.assertIs(type(res_q), str)
1668+
self.assertEqual(res_q, urllib.parse.quote(str(s)))
1669+
res_qp = urllib.parse.quote_plus(s)
1670+
self.assertIs(type(res_qp), str)
1671+
self.assertEqual(res_qp, urllib.parse.quote_plus(str(s)))
1672+
1673+
# str subclass overriding encode/rstrip/translate/isascii must bypass
1674+
# the fast path and use encode() as before.
1675+
class CustomEncodeStr(str):
1676+
def encode(self, encoding='utf-8', errors='strict'):
1677+
return b'custom'
1678+
def rstrip(self, chars=None):
1679+
raise AssertionError('rstrip should not be called on str subclass')
1680+
def translate(self, table):
1681+
raise AssertionError('translate should not be called on str subclass')
1682+
def isascii(self):
1683+
raise AssertionError('isascii should not be called on str subclass')
1684+
1685+
self.assertEqual(urllib.parse.quote(CustomEncodeStr('a b')), 'custom')
1686+
self.assertEqual(urllib.parse.quote_plus(CustomEncodeStr('a b')), 'custom')
1687+
1688+
class CustomSafeStr(str):
1689+
def encode(self, encoding='utf-8', errors='strict'):
1690+
return b'+ '
1691+
def __add__(self, other):
1692+
return CustomSafeStr(super().__add__(other))
1693+
1694+
self.assertEqual(
1695+
urllib.parse.quote('a+b/c', safe=CustomSafeStr('/')),
1696+
'a+b%2Fc',
1697+
)
1698+
self.assertEqual(
1699+
urllib.parse.quote_plus('a+b', safe=CustomSafeStr('')),
1700+
'a+b',
1701+
)
1702+
self.assertEqual(
1703+
urllib.parse.quote_plus('a+b c', safe=CustomSafeStr('')),
1704+
'a+b+c',
1705+
)
15921706

15931707
def test_issue14072(self):
15941708
p1 = urllib.parse.urlsplit('tel:+31-641044153')
@@ -1710,7 +1824,20 @@ def test_Quoter_repr(self):
17101824
self.assertIn('Quoter', repr(quoter))
17111825

17121826
def test_clear_cache_for_code_coverage(self):
1827+
urllib.parse.quote('a b/c')
1828+
urllib.parse.quote('a b/c', safe='')
1829+
urllib.parse.quote('a b/c', safe=':')
1830+
urllib.parse.quote_plus('a b/c')
1831+
urllib.parse.quote_plus('a b/c', safe=':')
1832+
self.assertGreater(urllib.parse._str_quoter_table.cache_info().currsize, 0)
17131833
urllib.parse.clear_cache()
1834+
self.assertEqual(urllib.parse._str_quoter_table.cache_info().currsize, 0)
1835+
self.assertIsNone(urllib.parse._STR_QUOTER_SLASH)
1836+
self.assertIsNone(urllib.parse._STR_QUOTER_EMPTY)
1837+
self.assertIsNone(urllib.parse._STR_QUOTER_PLUS_EMPTY)
1838+
# Re-populating after clear_cache works identically
1839+
self.assertEqual(urllib.parse.quote('a b/c'), 'a%20b/c')
1840+
self.assertEqual(urllib.parse.quote_plus('a b/c'), 'a+b%2Fc')
17141841

17151842
def test_urllib_parse_getattr_failure(self):
17161843
"""Test that urllib.parse.__getattr__() fails correctly."""

‎Lib/urllib/parse.py‎

Lines changed: 79 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -93,8 +93,13 @@
9393

9494
def clear_cache():
9595
"""Clear internal performance caches. Undocumented; some tests want it."""
96+
global _STR_QUOTER_SLASH, _STR_QUOTER_EMPTY, _STR_QUOTER_PLUS_EMPTY
9697
urlsplit.cache_clear()
9798
_byte_quoter_factory.cache_clear()
99+
_str_quoter_table.cache_clear()
100+
_STR_QUOTER_SLASH = None
101+
_STR_QUOTER_EMPTY = None
102+
_STR_QUOTER_PLUS_EMPTY = None
98103

99104
# Helpers for bytes handling
100105
# We deliberately require applications that
@@ -1018,6 +1023,29 @@ def unquote_plus(string, encoding='utf-8', errors='replace'):
10181023
_ALWAYS_SAFE_BYTES = bytes(_ALWAYS_SAFE)
10191024

10201025

1026+
_ALWAYS_SAFE_STR = ('ABCDEFGHIJKLMNOPQRSTUVWXYZ'
1027+
'abcdefghijklmnopqrstuvwxyz'
1028+
'0123456789'
1029+
'_.-~')
1030+
_ALWAYS_SAFE_SLASH_STR = _ALWAYS_SAFE_STR + '/'
1031+
_ASCII_ENCODINGS = frozenset(('utf-8', 'ascii', 'latin-1'))
1032+
1033+
def _make_str_quoter_table(safe, plus=False):
1034+
safe_set = set(_ALWAYS_SAFE_STR) | set(safe)
1035+
table = {b: f'%{b:02X}' for b in range(128) if chr(b) not in safe_set}
1036+
if plus:
1037+
table[32] = '+'
1038+
return table
1039+
1040+
_STR_QUOTER_SLASH = None
1041+
_STR_QUOTER_EMPTY = None
1042+
_STR_QUOTER_PLUS_EMPTY = None
1043+
1044+
@functools.lru_cache
1045+
def _str_quoter_table(safe, plus=False):
1046+
return _make_str_quoter_table(safe, plus)
1047+
1048+
10211049
class _Quoter(dict):
10221050
"""A mapping from bytes numbers (in range(0,256)) to strings.
10231051
@@ -1078,7 +1106,33 @@ def quote(string, safe='/', encoding=None, errors=None):
10781106
By default, encoding='utf-8' (characters are encoded with UTF-8), and
10791107
errors='strict' (unsupported characters raise a UnicodeEncodeError).
10801108
"""
1081-
if isinstance(string, str):
1109+
global _STR_QUOTER_SLASH, _STR_QUOTER_EMPTY
1110+
if type(string) is str:
1111+
if not string:
1112+
return string
1113+
if (string.isascii() and type(safe) is str and
1114+
(encoding is None or
1115+
(type(encoding) is str and encoding in _ASCII_ENCODINGS)) and
1116+
(errors is None or isinstance(errors, str))):
1117+
if safe == '/':
1118+
if not string.rstrip(_ALWAYS_SAFE_SLASH_STR):
1119+
return string
1120+
if (table := _STR_QUOTER_SLASH) is None:
1121+
table = _STR_QUOTER_SLASH = _make_str_quoter_table('/', False)
1122+
return string.translate(table)
1123+
if safe == '':
1124+
if not string.rstrip(_ALWAYS_SAFE_STR):
1125+
return string
1126+
if (table := _STR_QUOTER_EMPTY) is None:
1127+
table = _STR_QUOTER_EMPTY = _make_str_quoter_table('', False)
1128+
return string.translate(table)
1129+
return string.translate(_str_quoter_table(safe, False))
1130+
if encoding is None:
1131+
encoding = 'utf-8'
1132+
if errors is None:
1133+
errors = 'strict'
1134+
string = string.encode(encoding, errors)
1135+
elif isinstance(string, str):
10821136
if not string:
10831137
return string
10841138
if encoding is None:
@@ -1098,6 +1152,30 @@ def quote_plus(string, safe='', encoding=None, errors=None):
10981152
HTML form values. Plus signs in the original string are escaped unless
10991153
they are included in safe. It also does not have safe default to '/'.
11001154
"""
1155+
global _STR_QUOTER_PLUS_EMPTY
1156+
if type(string) is str:
1157+
if not string:
1158+
return string
1159+
if (string.isascii() and type(safe) is str and
1160+
(encoding is None or
1161+
(type(encoding) is str and encoding in _ASCII_ENCODINGS)) and
1162+
(errors is None or isinstance(errors, str))):
1163+
if safe == '':
1164+
if not string.rstrip(_ALWAYS_SAFE_STR):
1165+
return string
1166+
if (table := _STR_QUOTER_PLUS_EMPTY) is None:
1167+
table = _STR_QUOTER_PLUS_EMPTY = _make_str_quoter_table('', True)
1168+
return string.translate(table)
1169+
return string.translate(_str_quoter_table(safe, True))
1170+
has_space = ' ' in string
1171+
if has_space:
1172+
safe = safe + (' ' if isinstance(safe, str) else b' ')
1173+
if encoding is None:
1174+
encoding = 'utf-8'
1175+
if errors is None:
1176+
errors = 'strict'
1177+
res = quote_from_bytes(string.encode(encoding, errors), safe)
1178+
return res.replace(' ', '+') if has_space else res
11011179
# Check if ' ' in string, where string may either be a str or bytes. If
11021180
# there are no spaces, the regular quote will produce the right answer.
11031181
if ((isinstance(string, str) and ' ' not in string) or
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Speed up :func:`urllib.parse.quote`, :func:`urllib.parse.quote_plus`, and
2+
:func:`urllib.parse.urlencode` for ASCII :class:`str` inputs.

0 commit comments

Comments
 (0)