Skip to content

Instantly share code, notes, and snippets.

@flying-sheep
Last active August 13, 2024 17:39
Show Gist options
  • Save flying-sheep/8b6c3a7f124a1d90e3e2c75898303937 to your computer and use it in GitHub Desktop.
Save flying-sheep/8b6c3a7f124a1d90e3e2c75898303937 to your computer and use it in GitHub Desktop.
Find subpackages of a namespace package in a distribution
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