"csrc/balance_serve/sched/utils/all.hpp" did not exist on "8d0292aa4421504d8a48e6ca441a50f59032ddcf"
utils.py 1.64 KB
Newer Older
Baber's avatar
cleanup  
Baber committed
1
2
from __future__ import annotations

3
from functools import wraps
Baber's avatar
Baber committed
4
from inspect import getsource
5
6
7
8
from typing import Any, Callable, TypeVar


T = TypeVar("T")
Baber's avatar
Baber committed
9
10
11


def serialize_callable(
12
13
    value: Callable[..., T] | str, keep_callable=False
) -> Callable[..., T] | str:
Baber's avatar
Baber committed
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
    """Serializes a given function or string.

    If 'keep_callable' is True, the original callable is returned.
    Otherwise, attempts to return the source code of the callable using 'getsource'.
    If serialization fails, returns the string representation.
    """
    if keep_callable:
        return value
    else:
        try:
            return getsource(value)
        except (TypeError, OSError):
            return str(value)


29
30
31
def maybe_serialize(
    val: Callable[..., T] | Any, keep_callable=False
) -> Callable[..., T] | Any:
Baber's avatar
Baber committed
32
33
34
35
36
    """Conditionally serializes a value if it is callable."""

    return (
        serialize_callable(val, keep_callable=keep_callable) if callable(val) else val
    )
37
38


Baber's avatar
Baber committed
39
def create_mc_choices(choices: list[str], choice_delimiter: str = "\n") -> str:
40
41
42
    """Creates a multiple-choice question format from a list of choices."""
    formatted_choices = [f"{chr(65 + i)}. {choice}" for i, choice in enumerate(choices)]
    return choice_delimiter.join(formatted_choices)
43
44


Baber's avatar
Baber committed
45
46
47
48
def create_cloze_choices(choices: list[str], choice_delimiter: str = "\n") -> str:
    """Creates a cloze-style question format from a list of choices."""


49
50
51
52
53
54
55
56
def doc_to_closure(fn: Callable[..., T]) -> Callable[..., T]:
    """Closure that allows the function to be called with 'self'."""

    @wraps(fn)
    def closure(self: Any, *args, **kwargs):
        return fn(*args, **kwargs)

    return closure