All checks were successful
Standard CI tests / Packaging test - Kali Linux (pull_request) Successful in 3m49s
Standard CI tests / Packaging test - OpenSUSE Tumbleweed (pull_request) Successful in 3m36s
Standard CI tests / Packaging test - All supported platforms (pull_request) Successful in 0s
Standard CI tests / Packaging test - Kali Linux (push) Successful in 3m55s
Standard CI tests / Packaging test - OpenSUSE Tumbleweed (push) Successful in 3m26s
Standard CI tests / Packaging test - All supported platforms (push) Successful in 0s
- Remove package_name and package_path from the prototype of detect_modules(). They can and should be deduced from namespace['__name__'] and namespace['__path__'], respectively.- Make prefix default to None, which signifies "Don't filter by prefix".- Add an optional extend_namespace parameter, which will make the function append the module's __name__ to its __path__. This defaults to True, thereby adding a side effect to the function. Which is always wanted in the case for all callers of this function.Signed-off-by: Jan Lindemann <jan@janware.com>
48 lines
1.3 KiB
Python
48 lines
1.3 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 MutableMapping
|
|
from typing import Any
|
|
|
|
def detect_modules(
|
|
namespace: MutableMapping[str, Any],
|
|
prefix: str | None = None,
|
|
skip: set[str] | None = None,
|
|
*,
|
|
extend_namespace: bool = True,
|
|
) -> list[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)
|
|
|
|
namespace[module_name] = cls
|
|
ret.append(module_name)
|
|
|
|
return ret
|