jw-pkg/src/python/jw/pkg/lib/init.py
Jan Lindemann 0407215530
All checks were successful
CI / Packaging - Kali Linux (pull_request) Successful in 4m10s
CI / Packaging - OpenSUSE Tumbleweed (pull_request) Successful in 4m29s
CI / Packaging test (pull_request) Successful in 0s
CI / Packaging - Kali Linux (push) Successful in 4m5s
CI / Packaging - OpenSUSE Tumbleweed (push) Successful in 4m3s
CI / Packaging test (push) Successful in 0s
init.detect_modules(): Add base_types filter
Add a parameter "base_types" to detect_modules(), defaulting to None. If
it is not None, a module is only exported if its same-named object
inherits from one of the given types. Modules without a same-named class
are skipped instead of raising AttributeError, which covers helper
modules.

The return annotation becomes Sequence[str] instead of list[str] to
remove mutability for easier type checking.

Assisted-by: unsloth/Qwen3.8-27B-GGUF:Q4_K_M with pi.dev v0.84.2
Signed-off-by: Jan Lindemann <jan@janware.com>
2026-08-24 14:23:27 +02:00

54 lines
1.5 KiB
Python

from __future__ import annotations
import pkgutil
from importlib import import_module
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from collections.abc import Iterable, MutableMapping
from typing import Any, Sequence
def detect_modules(
namespace: MutableMapping[str, Any],
prefix: str | None = None,
skip: set[str] | None = None,
*,
base_types: Iterable[type[Any]] | None = None,
extend_namespace: bool = True,
) -> Sequence[str]:
package_name = namespace.get("__name__")
package_path = namespace.get("__path__")
if not isinstance(package_name, str):
raise TypeError("namespace must contain string __name__")
if package_path is None:
raise TypeError("namespace must be a package namespace with __path__")
if extend_namespace:
package_path = pkgutil.extend_path(package_path, package_name)
namespace["__path__"] = package_path
ret: list[str] = []
skip = skip or set()
for _finder, module_name, _ispkg in pkgutil.iter_modules(package_path):
if prefix is not None and not module_name.startswith(prefix):
continue
if module_name in skip:
continue
module = import_module(f".{module_name}", package_name)
cls = getattr(module, module_name, None)
if cls is None or not isinstance(cls, type):
continue
if base_types is not None and not issubclass(cls, tuple(base_types)):
continue
namespace[module_name] = cls
ret.append(module_name)
return ret