Last active
August 13, 2024 17:39
-
-
Save flying-sheep/8b6c3a7f124a1d90e3e2c75898303937 to your computer and use it in GitHub Desktop.
Find subpackages of a namespace package in a distribution
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import importlib | |
def find_subpackage(dist: str, ns_name: str): | |
"""Finds subpackages of a namespace package | |
Within a distribution `dist`, given a known toplevel namespace package `ns_name`, | |
this finds all 2 level deep package: | |
>>> list(find_subpackage("jaraco-classes", "jaraco")) | |
["jaraco.classes"] | |
""" | |
for f in importlib.metadata.files(dist): | |
if f.suffix != ".py": | |
continue | |
stem = f.with_suffix("") | |
if len(stem.parts) == 3 and stem.name == "__init__": | |
stem = stem.parent | |
if len(stem.parts) == 2: | |
yield str(stem).replace("/", ".") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment