]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
gh-143658: Use `str.lower` and `replace` to further improve performance of `importlib...
authorHugo van Kemenade <1324225+hugovk@users.noreply.github.com>
Fri, 6 Feb 2026 17:38:58 +0000 (19:38 +0200)
committerGitHub <noreply@github.com>
Fri, 6 Feb 2026 17:38:58 +0000 (19:38 +0200)
Co-authored-by: Henry Schreiner <henryschreineriii@gmail.com>
Lib/importlib/metadata/__init__.py
Misc/NEWS.d/next/Library/2026-01-20-20-54-46.gh-issue-143658.v8i1jE.rst [new file with mode: 0644]

index 9b723b4ec15e12f5dd98f06248f91ce03e051fd1..7cf4d29d330c91e206f4cb4d5204c0ddc912a94c 100644 (file)
@@ -890,14 +890,6 @@ class Lookup:
         return itertools.chain(infos, eggs)
 
 
-# Translation table for Prepared.normalize: lowercase and
-# replace "-" (hyphen) and "." (dot) with "_" (underscore).
-_normalize_table = str.maketrans(
-    "ABCDEFGHIJKLMNOPQRSTUVWXYZ-.",
-    "abcdefghijklmnopqrstuvwxyz__",
-)
-
-
 class Prepared:
     """
     A prepared search query for metadata on a possibly-named package.
@@ -933,9 +925,8 @@ class Prepared:
         """
         PEP 503 normalization plus dashes as underscores.
         """
-        # Emulates ``re.sub(r"[-_.]+", "-", name).lower()`` from PEP 503
-        # About 3x faster, safe since packages only support alphanumeric characters
-        value = name.translate(_normalize_table)
+        # Much faster than re.sub, and even faster than str.translate
+        value = name.lower().replace("-", "_").replace(".", "_")
         # Condense repeats (faster than regex)
         while "__" in value:
             value = value.replace("__", "_")
diff --git a/Misc/NEWS.d/next/Library/2026-01-20-20-54-46.gh-issue-143658.v8i1jE.rst b/Misc/NEWS.d/next/Library/2026-01-20-20-54-46.gh-issue-143658.v8i1jE.rst
new file mode 100644 (file)
index 0000000..8935b4c
--- /dev/null
@@ -0,0 +1,4 @@
+:mod:`importlib.metadata`: Use :meth:`str.lower` and :meth:`str.replace` to
+further improve performance of
+:meth:`!importlib.metadata.Prepared.normalize`. Patch by Hugo van Kemenade
+and Henry Schreiner.