Skip to content

Commit 001db0d

Browse files
hugovkhenryiii
authored andcommitted
gh-143658: Use str.lower and replace to further improve performance of importlib.metadata.Prepared.normalized (#144083)
Co-authored-by: Henry Schreiner <henryschreineriii@gmail.com>
1 parent 3e7f3ac commit 001db0d

File tree

2 files changed

+6
-11
lines changed

2 files changed

+6
-11
lines changed
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
:mod:`importlib.metadata`: Use :meth:`str.lower` and :meth:`str.replace` to
2+
further improve performance of
3+
:meth:`!importlib.metadata.Prepared.normalize`. Patch by Hugo van Kemenade
4+
and Henry Schreiner.

importlib_metadata/__init__.py

Lines changed: 2 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -894,14 +894,6 @@ def search(self, prepared: Prepared):
894894
return itertools.chain(infos, eggs)
895895

896896

897-
# Translation table for Prepared.normalize: lowercase and
898-
# replace "-" (hyphen) and "." (dot) with "_" (underscore).
899-
_normalize_table = str.maketrans(
900-
"ABCDEFGHIJKLMNOPQRSTUVWXYZ-.",
901-
"abcdefghijklmnopqrstuvwxyz__",
902-
)
903-
904-
905897
class Prepared:
906898
"""
907899
A prepared search query for metadata on a possibly-named package.
@@ -937,9 +929,8 @@ def normalize(name):
937929
"""
938930
PEP 503 normalization plus dashes as underscores.
939931
"""
940-
# Emulates ``re.sub(r"[-_.]+", "-", name).lower()`` from PEP 503
941-
# About 3x faster, safe since packages only support alphanumeric characters
942-
value = name.translate(_normalize_table)
932+
# Much faster than re.sub, and even faster than str.translate
933+
value = name.lower().replace("-", "_").replace(".", "_")
943934
# Condense repeats (faster than regex)
944935
while "__" in value:
945936
value = value.replace("__", "_")

0 commit comments

Comments
 (0)