Skip to content

Commit bd6916a

Browse files
committed
Switch to bytes.translate() based approach
1 parent 8811463 commit bd6916a

File tree

2 files changed

+9
-12
lines changed

2 files changed

+9
-12
lines changed

Lib/shlex.py

Lines changed: 6 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -317,20 +317,16 @@ def join(split_command):
317317
return ' '.join(quote(arg) for arg in split_command)
318318

319319

320-
def _find_unsafe(s, /):
321-
# this function replaces itself with the compiled pattern on execution,
322-
# to allow as deferred import of re for performance
323-
global _find_unsafe
324-
import re
325-
_find_unsafe = re.compile(r'[^\w@%+=:,./-]', re.ASCII).search
326-
return _find_unsafe(s)
327-
328-
329320
def quote(s):
330321
"""Return a shell-escaped version of the string *s*."""
331322
if not s:
332323
return "''"
333-
if _find_unsafe(s) is None:
324+
325+
# Use bytes.translate() for performance
326+
safe_chars = (b'%+,-./0123456789:=@'
327+
b'ABCDEFGHIJKLMNOPQRSTUVWXYZ_'
328+
b'abcdefghijklmnopqrstuvwxyz')
329+
if not s.encode().translate(None, delete=safe_chars):
334330
return s
335331

336332
# use single quotes, and put single quotes into double quotes
Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,3 @@
1-
Improve import times by up to 33x for the :mod:`shlex` module. Patch by Adam
2-
Turner.
1+
Improve import times by up to 33x for the :mod:`shlex` module,
2+
and improve the performance of :func:`shlex.quote` by up to 12x.
3+
Patch by Adam Turner.

0 commit comments

Comments
 (0)