utils.py 1.38 KB
Newer Older
Baber's avatar
cleanup  
Baber committed
1
2
from __future__ import annotations

Baber's avatar
Baber committed
3
from inspect import getsource
Baber's avatar
cleanup  
Baber committed
4
from typing import Any, Callable
Baber's avatar
Baber committed
5
6
7


def serialize_callable(
Baber's avatar
cleanup  
Baber committed
8
9
    value: Callable[..., Any] | str, keep_callable=False
) -> Callable[..., Any] | str:
Baber's avatar
Baber committed
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
    """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)


Baber's avatar
cleanup  
Baber committed
25
def maybe_serialize(val: Callable | Any, keep_callable=False) -> Callable | Any:
Baber's avatar
Baber committed
26
27
28
29
30
    """Conditionally serializes a value if it is callable."""

    return (
        serialize_callable(val, keep_callable=keep_callable) if callable(val) else val
    )
31
32
33
34
35
36
37
38
39
40
41
42
43


def create_mc_choices(choices: list[str], choice_delimiter: str | None = "\n") -> str:
    """Creates a multiple-choice question format from a list of choices."""
    if len(choices) < 2:
        raise ValueError(
            "At least two choices are required for a multiple-choice question."
        )
    if choice_delimiter is None:
        choice_delimiter = "\n"

    formatted_choices = [f"{chr(65 + i)}. {choice}" for i, choice in enumerate(choices)]
    return choice_delimiter.join(formatted_choices)