Skip to content

util

Various utilities.

cache_result(func)

Cache result of function to recall on reuse.

A better version of the stateful lambda decorator. (@lambda : ())

Uses a generated class w/ unique name to store state, modifying the generated class defintion so state persists.

Returns:

Type Description
Callable

Result on first use, cached state on second.

Source code in client/ayon_comfyui/api/util.py
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
def cache_result(func: Callable) -> Callable:
    """Cache result of function to recall on reuse.

    A better version of the stateful lambda decorator. (@lambda _: _())

    Uses a generated class w/ unique name to store state,
    modifying the generated class defintion so state persists.

    Returns:
        Result on first use, cached state on second.
    """
    cls_dict = {"_cache": None, "_set": False}
    storage_t = type("cache_" + func.__qualname__, (), cls_dict)

    @wraps(func)
    def _cache_func(*args, **kwargs):  # noqa: ANN202, ANN002, ANN003
        if not storage_t._set:  # noqa: SLF001
            result = func(*args, **kwargs)
            storage_t._cache = result  # noqa: SLF001
            storage_t._set = True  # noqa: SLF001
            return result
        return storage_t._cache  # noqa: SLF001

    return _cache_func

demangle_method(cls_or_instance, function_name, *, use_mro=False)

Return function object by name, demangled.

Evil way to grab a method preceded by 2 underscores.

Example:

class A:
    def __func(self, arg):
        ...

class A_A(A):
    def func(self, arg):
        return demangle_method(self,"__func")(self, arg)
Source code in client/ayon_comfyui/api/util.py
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
def demangle_method(
    cls_or_instance: Any,  # noqa: ANN401
    function_name: str,
    *,
    use_mro: bool = False,
) -> Callable | None:
    """Return function object by name, demangled.

    Evil way to grab a method preceded by 2 underscores.

    Example:
    ```
    class A:
        def __func(self, arg):
            ...

    class A_A(A):
        def func(self, arg):
            return demangle_method(self,"__func")(self, arg)
    ```
    """
    # Assert if class
    try:
        issubclass(cls_or_instance, object)
    except TypeError:
        cls_or_instance = cls_or_instance.__class__

    bases: tuple = (
        cls_or_instance.__mro__ if use_mro else cls_or_instance.__bases__
    )

    for b_cls in bases:
        name = b_cls.__qualname__
        demangle = f"_{name}{function_name}"
        if demangle in dir(b_cls):
            func = getattr(b_cls, demangle)
            if callable(func):
                return func
            break
    return None

extract_default_kwargs(func)

Returns a dict with default arguments to a function.

Source code in client/ayon_comfyui/api/util.py
82
83
84
85
86
87
88
89
90
91
def extract_default_kwargs(func: Callable) -> dict[str, Any]:
    """Returns a dict with default arguments to a function."""
    params = inspect.signature(func).parameters
    kwargs = {}
    for param in params.values():
        if param.default == inspect.Parameter.empty:
            continue
        kwargs[param.name] = param.default

    return kwargs

syncify(coro)

Transform async function into a synchronous function.

Returns:

Type Description
Callable

Blocking version of async function.

Source code in client/ayon_comfyui/api/util.py
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
def syncify(coro: Coroutine) -> Callable:
    """Transform async function into a synchronous function.

    Returns:
        Blocking version of async function.
    """

    @wraps(coro)
    def _inner_(*args: list[Any], **kwargs: dict[str, Any]) -> Any:  # noqa: ANN401
        _loop_ = asyncio.new_event_loop()
        asyncio.set_event_loop(_loop_)
        return _loop_.run_until_complete(coro(*args, **kwargs))

    return _inner_