Class Utils

Scan a package for class_utils definitions without importing all modules at once. Returns a dict mapping class_utils name to (module_name, class_name).

Source code in utils\class_utils\build_class_index.py
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
def build_class_index(package_name: str):
    """
    Scan a package for class_utils definitions without importing all modules at once.
    Returns a dict mapping class_utils name to (module_name, class_name).
    """
    index = {}
    package = importlib.import_module(package_name)

    for _, module_name, _ in pkgutil.walk_packages(package.__path__, package.__name__ + "."):
        module = importlib.import_module(module_name)  # minimal import to inspect
        for name, obj in inspect.getmembers(module, inspect.isclass):
            if obj.__module__ == module.__name__:
                index[name] = (module_name, name)
    return index

Given a class_utils index (from build_class_index) and a class_utils name, import and return the class_utils object.

Source code in utils\class_utils\load_class_from_index.py
 4
 5
 6
 7
 8
 9
10
11
12
13
14
def load_class_from_index(class_index, class_name: str):
    """
    Given a class_utils index (from build_class_index) and a class_utils name,
    import and return the class_utils object.
    """
    if class_name not in class_index:
        raise ValueError(f"Class '{class_name}' not found.")

    module_name, cls_name = class_index[class_name]
    module = importlib.import_module(module_name)
    return getattr(module, cls_name)

Return the names of public methods defined directly on a class.

Parameters

cls: Class whose methods should be inspected. ignore: Optional list of method names to exclude from the result.

Returns

list[str] Names of methods defined on cls that are: - plain functions (no descriptors), - not dunder methods, - not starting with set, - not listed in ignore.

Source code in utils\class_utils\get_class_methods.py
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
def get_class_methods(cls, ignore=[]) -> list:
    """
    Return the names of public methods defined directly on a class.

    Parameters
    ----------
    cls:
        Class whose methods should be inspected.
    ignore:
        Optional list of method names to exclude from the result.

    Returns
    -------
    list[str]
        Names of methods defined on ``cls`` that are:
        - plain functions (no descriptors),
        - not dunder methods,
        - not starting with ``set``,
        - not listed in ``ignore``.
    """
    methods = []
    for name, func in cls.__dict__.items():
        # Skip items that are not of the function type
        if type(func) != FunctionType:
            continue
        # ignore dunder_methods, setters and explicitly ignored function names
        if not name.startswith('_') and not name.startswith('set') and name not in ignore:
            methods.append(name)

    return methods