|
| 1 | +# Copyright (c) DataLab Platform Developers, BSD 3-Clause license, see LICENSE file. |
| 2 | + |
| 3 | +""" |
| 4 | +.. Computation function decorator and utilities |
| 5 | +(see parent package :mod:`sigima.computation`) |
| 6 | +""" |
| 7 | + |
| 8 | +from __future__ import annotations |
| 9 | + |
| 10 | +import dataclasses |
| 11 | +import functools |
| 12 | +import importlib |
| 13 | +import inspect |
| 14 | +import os.path as osp |
| 15 | +import pkgutil |
| 16 | +import sys |
| 17 | +from types import ModuleType |
| 18 | +from typing import Callable, Optional, TypeVar |
| 19 | + |
| 20 | +if sys.version_info >= (3, 10): |
| 21 | + # Use ParamSpec from typing module in Python 3.10+ |
| 22 | + from typing import ParamSpec |
| 23 | +else: |
| 24 | + # Use ParamSpec from typing_extensions module in Python < 3.10 |
| 25 | + from typing_extensions import ParamSpec |
| 26 | + |
| 27 | +# Marker attribute used by @computation_function and introspection |
| 28 | +COMPUTATION_METADATA_ATTR = "__computation_function_metadata" |
| 29 | + |
| 30 | +P = ParamSpec("P") |
| 31 | +R = TypeVar("R") |
| 32 | + |
| 33 | + |
| 34 | +@dataclasses.dataclass(frozen=True) |
| 35 | +class ComputationMetadata: |
| 36 | + """Metadata for a computation function. |
| 37 | +
|
| 38 | + Attributes: |
| 39 | + name: The name of the computation function. |
| 40 | + description: A description or docstring for the computation function. |
| 41 | + """ |
| 42 | + |
| 43 | + name: str |
| 44 | + description: str |
| 45 | + |
| 46 | + |
| 47 | +def computation_function( |
| 48 | + *, |
| 49 | + name: Optional[str] = None, |
| 50 | + description: Optional[str] = None, |
| 51 | +) -> Callable[[Callable[P, R]], Callable[P, R]]: |
| 52 | + """Decorator to mark a function as a Sigima computation function. |
| 53 | +
|
| 54 | + Args: |
| 55 | + name: Optional name to override the function name. |
| 56 | + description: Optional docstring override or additional description. |
| 57 | +
|
| 58 | + Returns: |
| 59 | + The wrapped function, tagged with a marker attribute. |
| 60 | + """ |
| 61 | + |
| 62 | + def decorator(f: Callable[P, R]) -> Callable[P, R]: |
| 63 | + """Decorator to mark a function as a Sigima computation function. |
| 64 | + This decorator adds a marker attribute to the function, allowing |
| 65 | + it to be identified as a computation function. |
| 66 | + It also allows for optional name and description overrides. |
| 67 | + The function can be used as a decorator or as a standalone function. |
| 68 | + """ |
| 69 | + |
| 70 | + @functools.wraps(f) |
| 71 | + def wrapper(*args: P.args, **kwargs: P.kwargs) -> R: |
| 72 | + return f(*args, **kwargs) |
| 73 | + |
| 74 | + metadata = ComputationMetadata( |
| 75 | + name=name or f.__name__, description=description or f.__doc__ |
| 76 | + ) |
| 77 | + setattr(wrapper, COMPUTATION_METADATA_ATTR, metadata) |
| 78 | + return wrapper |
| 79 | + |
| 80 | + return decorator |
| 81 | + |
| 82 | + |
| 83 | +def is_computation_function(function: Callable) -> bool: |
| 84 | + """Check if a function is a Sigima computation function. |
| 85 | +
|
| 86 | + Args: |
| 87 | + function: The function to check. |
| 88 | +
|
| 89 | + Returns: |
| 90 | + True if the function is a Sigima computation function, False otherwise. |
| 91 | + """ |
| 92 | + return getattr(function, COMPUTATION_METADATA_ATTR, None) is not None |
| 93 | + |
| 94 | + |
| 95 | +def get_computation_metadata(function: Callable) -> ComputationMetadata: |
| 96 | + """Get the metadata of a Sigima computation function. |
| 97 | +
|
| 98 | + Args: |
| 99 | + function: The function to get metadata from. |
| 100 | +
|
| 101 | + Returns: |
| 102 | + Computation function metadata. |
| 103 | +
|
| 104 | + Raises: |
| 105 | + ValueError: If the function is not a Sigima computation function. |
| 106 | + """ |
| 107 | + metadata = getattr(function, COMPUTATION_METADATA_ATTR, None) |
| 108 | + if not isinstance(metadata, ComputationMetadata): |
| 109 | + raise ValueError( |
| 110 | + f"The function {function.__name__} is not a Sigima computation function." |
| 111 | + ) |
| 112 | + return metadata |
| 113 | + |
| 114 | + |
| 115 | +def find_computation_functions( |
| 116 | + module: ModuleType | None = None, |
| 117 | +) -> list[tuple[str, Callable]]: |
| 118 | + """Find all computation functions in the `sigima.proc` package. |
| 119 | +
|
| 120 | + This function uses introspection to locate all functions decorated with |
| 121 | + `@computation_function` in the `sigima.proc` package and its subpackages. |
| 122 | +
|
| 123 | + Args: |
| 124 | + module: Optional module to search in. If None, the current module is used. |
| 125 | +
|
| 126 | + Returns: |
| 127 | + A list of tuples, each containing the function name and the function object. |
| 128 | + """ |
| 129 | + functions = [] |
| 130 | + if module is None: |
| 131 | + path = [osp.dirname(__file__)] |
| 132 | + else: |
| 133 | + path = module.__path__ |
| 134 | + objs = [] |
| 135 | + for _, modname, _ in pkgutil.walk_packages(path=path, prefix=__name__ + "."): |
| 136 | + try: |
| 137 | + module = importlib.import_module(modname) |
| 138 | + except Exception: # pylint: disable=broad-except |
| 139 | + continue |
| 140 | + for name, obj in inspect.getmembers(module, inspect.isfunction): |
| 141 | + if is_computation_function(obj): |
| 142 | + if obj in objs: # Avoid double entries for the same function |
| 143 | + continue |
| 144 | + objs.append(obj) |
| 145 | + functions.append((modname, name, obj.__doc__)) |
| 146 | + return functions |
0 commit comments