lib.init.detect_modules(): Add function
Not all __init__.py modules are generated by python-tools.sh, some are needed early to make jw-pkg useful without generation, notably in jw.pkg.cmds.
Add detect_modules() to unify that detection, and place it into a minimal module lib.init to not increase startup time cost.
Signed-off-by: Jan Lindemann <jan@janware.com>
This commit is contained in:
parent
fc6f2fbb65
commit
13ec34cc57
5 changed files with 68 additions and 42 deletions
36
src/python/jw/pkg/lib/init.py
Normal file
36
src/python/jw/pkg/lib/init.py
Normal file
|
|
@ -0,0 +1,36 @@
|
|||
from __future__ import annotations
|
||||
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import MutableMapping
|
||||
from typing import Any, Iterable
|
||||
|
||||
def detect_modules(
|
||||
package_name: str,
|
||||
package_path: Iterable[str],
|
||||
namespace: MutableMapping[str, Any],
|
||||
prefix: str,
|
||||
skip: set[str] | None = None,
|
||||
) -> list[str]:
|
||||
|
||||
import importlib
|
||||
import pkgutil
|
||||
|
||||
ret: list[str] = []
|
||||
skip = skip or set()
|
||||
|
||||
for _finder, module_name, _ispkg in pkgutil.iter_modules(package_path):
|
||||
if not module_name.startswith(prefix):
|
||||
continue
|
||||
|
||||
if module_name in skip:
|
||||
continue
|
||||
|
||||
module = importlib.import_module(f'.{module_name}', package_name)
|
||||
cls = getattr(module, module_name)
|
||||
|
||||
namespace[module_name] = cls
|
||||
ret.append(module_name)
|
||||
|
||||
return ret
|
||||
Loading…
Add table
Add a link
Reference in a new issue