Skip to content

Commit 851b921

Browse files
committed
Extract _topmost and _get_toplevel_name functions.
1 parent 4ebe490 commit 851b921

File tree

1 file changed

+27
-4
lines changed

1 file changed

+27
-4
lines changed

importlib_metadata/__init__.py

Lines changed: 27 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -973,11 +973,34 @@ def _top_level_declared(dist):
973973
return (dist.read_text('top_level.txt') or '').split()
974974

975975

976+
def _topmost(name: PackagePath) -> Optional[str]:
977+
"""
978+
Return the top-most parent as long as there is a parent.
979+
"""
980+
top, *rest = name.parts
981+
return top if rest else None
982+
983+
984+
def _get_toplevel_name(name: PackagePath) -> str:
985+
"""
986+
Infer a possibly importable module name from a name presumed on
987+
sys.path.
988+
989+
>>> _get_toplevel_name(PackagePath('foo.py'))
990+
'foo'
991+
>>> _get_toplevel_name(PackagePath('foo.pyc'))
992+
'foo'
993+
>>> _get_toplevel_name(PackagePath('foo/__init__.py'))
994+
'foo'
995+
"""
996+
return _topmost(name) or (
997+
# python/typeshed#10328
998+
inspect.getmodulename(name) # type: ignore
999+
)
1000+
1001+
9761002
def _top_level_inferred(dist):
977-
opt_names = {
978-
f.parts[0] if len(f.parts) > 1 else inspect.getmodulename(f)
979-
for f in always_iterable(dist.files)
980-
}
1003+
opt_names = set(map(_get_toplevel_name, always_iterable(dist.files)))
9811004

9821005
@pass_none
9831006
def importable_name(name):

0 commit comments

Comments
 (0)