Skip to content

Commit d1480ad

Browse files
bpo-44246: Entry points performance improvements. (GH-26467)
From importlib_metadata 4.3.1. (cherry picked from commit 410b70d) Co-authored-by: Jason R. Coombs <[email protected]>
1 parent 3f592c3 commit d1480ad

File tree

3 files changed

+30
-1
lines changed

3 files changed

+30
-1
lines changed

Lib/importlib/metadata/__init__.py

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -493,6 +493,11 @@ def name(self):
493493
"""Return the 'Name' metadata for the distribution package."""
494494
return self.metadata['Name']
495495

496+
@property
497+
def _normalized_name(self):
498+
"""Return a normalized version of the name."""
499+
return Prepared.normalize(self.name)
500+
496501
@property
497502
def version(self):
498503
"""Return the 'Version' metadata for the distribution package."""
@@ -795,6 +800,22 @@ def read_text(self, filename):
795800
def locate_file(self, path):
796801
return self._path.parent / path
797802

803+
@property
804+
def _normalized_name(self):
805+
"""
806+
Performance optimization: where possible, resolve the
807+
normalized name from the file system path.
808+
"""
809+
stem = os.path.basename(str(self._path))
810+
return self._name_from_stem(stem) or super()._normalized_name
811+
812+
def _name_from_stem(self, stem):
813+
name, ext = os.path.splitext(stem)
814+
if ext not in ('.dist-info', '.egg-info'):
815+
return
816+
name, sep, rest = stem.partition('-')
817+
return name
818+
798819

799820
def distribution(distribution_name):
800821
"""Get the ``Distribution`` instance for the named package.
@@ -849,7 +870,8 @@ def entry_points(**params) -> Union[EntryPoints, SelectableGroups]:
849870
850871
:return: EntryPoints or SelectableGroups for all installed packages.
851872
"""
852-
unique = functools.partial(unique_everseen, key=operator.attrgetter('name'))
873+
norm_name = operator.attrgetter('_normalized_name')
874+
unique = functools.partial(unique_everseen, key=norm_name)
853875
eps = itertools.chain.from_iterable(
854876
dist.entry_points for dist in unique(distributions())
855877
)

Lib/test/test_importlib/test_zip.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -76,3 +76,7 @@ def test_files(self):
7676
for file in files('example'):
7777
path = str(file.dist.locate_file(file))
7878
assert '.egg/' in path, path
79+
80+
def test_normalized_name(self):
81+
dist = distribution('example')
82+
assert dist._normalized_name == 'example'
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
In importlib.metadata.entry_points, de-duplication of distributions no
2+
longer requires loading the full metadata for PathDistribution objects,
3+
improving entry point loading performance by ~10x.

0 commit comments

Comments
 (0)