Skip to content

Commit b95d70b

Browse files
hugovkhenryiii
andcommitted
Use str.lower and replace to further improve performance of importlib.metadata.Prepared.normalized
Co-authored-by: Henry Schreiner <henryschreineriii@gmail.com>
1 parent 27a7160 commit b95d70b

File tree

2 files changed

+6
-11
lines changed

2 files changed

+6
-11
lines changed

Lib/importlib/metadata/__init__.py

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

892892

893-
# Translation table for Prepared.normalize: lowercase and
894-
# replace "-" (hyphen) and "." (dot) with "_" (underscore).
895-
_normalize_table = str.maketrans(
896-
"ABCDEFGHIJKLMNOPQRSTUVWXYZ-.",
897-
"abcdefghijklmnopqrstuvwxyz__",
898-
)
899-
900-
901893
class Prepared:
902894
"""
903895
A prepared search query for metadata on a possibly-named package.
@@ -933,9 +925,8 @@ def normalize(name):
933925
"""
934926
PEP 503 normalization plus dashes as underscores.
935927
"""
936-
# Emulates ``re.sub(r"[-_.]+", "-", name).lower()`` from PEP 503
937-
# About 3x faster, safe since packages only support alphanumeric characters
938-
value = name.translate(_normalize_table)
928+
# Much faster than re.sub, and even faster than str.translate
929+
value = name.lower().replace("-", "_").replace(".", "_")
939930
# Condense repeats (faster than regex)
940931
while "__" in value:
941932
value = value.replace("__", "_")
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.

0 commit comments

Comments
 (0)