Skip to content

gh-118761: Optimise import time for shlex #132036

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 6 commits into from
Apr 24, 2025
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 6 additions & 10 deletions Lib/shlex.py
Original file line number Diff line number Diff line change
Expand Up @@ -317,20 +317,16 @@ def join(split_command):
return ' '.join(quote(arg) for arg in split_command)


def _find_unsafe(s, /):
# this function replaces itself with the compiled pattern on execution,
# to allow as deferred import of re for performance
global _find_unsafe
import re
_find_unsafe = re.compile(r'[^\w@%+=:,./-]', re.ASCII).search
return _find_unsafe(s)


def quote(s):
"""Return a shell-escaped version of the string *s*."""
if not s:
return "''"
if _find_unsafe(s) is None:

# Use bytes.translate() for performance
safe_chars = (b'%+,-./0123456789:=@'
b'ABCDEFGHIJKLMNOPQRSTUVWXYZ_'
b'abcdefghijklmnopqrstuvwxyz')
if not s.encode().translate(None, delete=safe_chars):
return s

# use single quotes, and put single quotes into double quotes
Expand Down
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
Improve import times by up to 33x for the :mod:`shlex` module. Patch by Adam
Turner.
Improve import times by up to 33x for the :mod:`shlex` module,
and improve the performance of :func:`shlex.quote` by up to 12x.
Patch by Adam Turner.
Loading