Skip to content

Commit 9f19c5f

Browse files
authored
Support namespace package in sys_info (#222)
* Support namespace package in sys_info * fix
1 parent 480b42a commit 9f19c5f

1 file changed

Lines changed: 24 additions & 2 deletions

File tree

src/template/utils/config.py

Lines changed: 24 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
import sys
55
import tomllib
66
from functools import lru_cache, partial
7-
from importlib.metadata import metadata, requires, version
7+
from importlib.metadata import PackageNotFoundError, metadata, requires, version
88
from importlib.util import find_spec
99
from pathlib import Path
1010
from typing import TYPE_CHECKING
@@ -47,7 +47,10 @@ def sys_info(
4747

4848
ljust = 26
4949
out = partial(print, end="", file=fid)
50-
package = __package__.split(".")[0] if package is None else package
50+
if package is None:
51+
package = _find_distribution_name(__package__)
52+
if "-" in package:
53+
package = package.replace("-", "_")
5154

5255
# OS information - requires python 3.8 or above
5356
out("Platform:".ljust(ljust) + platform.platform() + "\n")
@@ -179,6 +182,25 @@ def _list_dependencies_info(
179182
out(f"Not installed: {', '.join(not_found)}\n")
180183

181184

185+
def _find_distribution_name(module_package: str) -> str:
186+
"""Find the distribution name from a module's ``__package__``.
187+
188+
Tries progressively shorter prefixes until finding one with valid metadata.
189+
Handles both regular packages (e.g., ``template.utils`` -> ``template``) and
190+
namespace packages (e.g., ``sphinxcontrib.pydantic.utils`` ->
191+
``sphinxcontrib.pydantic``).
192+
"""
193+
parts = module_package.split(".")
194+
for i in range(len(parts), 0, -1):
195+
candidate = ".".join(parts[:i])
196+
try:
197+
version(candidate)
198+
return candidate
199+
except PackageNotFoundError:
200+
continue
201+
return module_package
202+
203+
182204
@lru_cache(maxsize=1)
183205
def _get_gpu_info() -> tuple[str | None, str | None]:
184206
"""Get the GPU information."""

0 commit comments

Comments
 (0)