https://github.com/python/cpython/commit/28fb13cb33d569720938258db68956b5f9c9eb40
commit: 28fb13cb33d569720938258db68956b5f9c9eb40
branch: main
author: Hugo van Kemenade <[email protected]>
committer: hugovk <[email protected]>
date: 2026-02-06T19:38:58+02:00
summary:

gh-143658: Use `str.lower` and `replace` to further improve performance of 
`importlib.metadata.Prepared.normalized` (#144083)

Co-authored-by: Henry Schreiner <[email protected]>

files:
A Misc/NEWS.d/next/Library/2026-01-20-20-54-46.gh-issue-143658.v8i1jE.rst
M Lib/importlib/metadata/__init__.py

diff --git a/Lib/importlib/metadata/__init__.py 
b/Lib/importlib/metadata/__init__.py
index 9b723b4ec15e12..7cf4d29d330c91 100644
--- a/Lib/importlib/metadata/__init__.py
+++ b/Lib/importlib/metadata/__init__.py
@@ -890,14 +890,6 @@ def search(self, prepared: Prepared):
         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 @@ def normalize(name):
         """
         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
index 00000000000000..8935b4c655023a
--- /dev/null
+++ b/Misc/NEWS.d/next/Library/2026-01-20-20-54-46.gh-issue-143658.v8i1jE.rst
@@ -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.

_______________________________________________
Python-checkins mailing list -- [email protected]
To unsubscribe send an email to [email protected]
https://mail.python.org/mailman3//lists/python-checkins.python.org
Member address: [email protected]

Reply via email to