Saltar a contenido

Utils Module

add_single_quotes_to_list_elements(lst)

Add single quotes to each element in a list or tuple.

Parameters:

Name Type Description Default
lst List | tuple

List or tuple of elements to be quoted.

required

Returns:
List: List of elements with single quotes added.

Source code in devices\raspberry_pi_5\src\utils\__init__.py
66
67
68
69
70
71
72
73
74
75
def add_single_quotes_to_list_elements(lst: List | tuple) -> List:
    """
    Add single quotes to each element in a list or tuple.

    Args:
        lst (List | tuple): List or tuple of elements to be quoted.
    Returns:
        List: List of elements with single quotes added.
    """
    return [f"'{item}'" for item in lst]

get_local_ip()

Get the local IP address of the machine.

Returns:

Name Type Description
str str | None | Any

Local IP address as a string.

Source code in devices\raspberry_pi_5\src\utils\__init__.py
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
def get_local_ip() -> str | None | Any:
    """
    Get the local IP address of the machine.

    Returns:
        str: Local IP address as a string.
    """
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    try:
        # Doesn't need to be reachable
        s.connect(('8.8.8.8', 80))
        ip = s.getsockname()[0]

    except Exception:
        ip = '127.0.0.1'

    finally:
        s.close()

    return ip

is_instance(obj, class_or_tuple)

Check if the object is an instance of the specified class or tuple of classes,
unwrapping proxy objects if necessary.

Parameters:

Name Type Description Default
obj object

The object to check.

required
class_or_tuple type | UnionType | tuple[Any, ...]

The class or tuple of classes to check against.

required

Raises:
TypeError: If the object is not an instance of the specified class or tuple of classes.

Source code in devices\raspberry_pi_5\src\utils\__init__.py
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
def is_instance(
    obj: object,
    class_or_tuple: type | UnionType | tuple[Any, ...]
) -> None:
    """
    Check if the object is an instance of the specified class or tuple of classes,
    unwrapping proxy objects if necessary.

    Args:
        obj (object): The object to check.
        class_or_tuple (type | UnionType | tuple[Any, ...]): The class or tuple of classes to check against.
    Raises:
        TypeError: If the object is not an instance of the specified class or tuple of classes.
    """
    # Unwrap common proxy objects (e.g., multiprocessing.Manager proxies)
    if hasattr(obj, '_getvalue'):
        obj = obj._getvalue()
    elif hasattr(obj, '_get_obj'):
        obj = obj._get_obj()

    if not isinstance(obj, class_or_tuple):
        raise TypeError(
            f"Expected type {class_or_tuple}, got {type(obj)} for object {obj}"
        )

is_subclass(cls, class_or_tuple)

Check if the class is a subclass of the specified class or tuple of classes.

Parameters:

Name Type Description Default
cls type

The class to check.

required
class_or_tuple type | UnionType | tuple[Any, ...]

The class or tuple of classes to check against.

required

Raises:
TypeError: If the class is not a subclass of the specified class or tuple of classes.

Source code in devices\raspberry_pi_5\src\utils\__init__.py
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
def is_subclass(
    cls: type,
    class_or_tuple: type | UnionType | tuple[Any, ...]
) -> None:
    """
    Check if the class is a subclass of the specified class or tuple of classes.

    Args:
        cls (type): The class to check.
        class_or_tuple (type | UnionType | tuple[Any, ...]): The class or tuple of classes to check against.
    Raises:
        TypeError: If the class is not a subclass of the specified class or tuple of classes.
    """
    if not issubclass(cls, class_or_tuple):
        raise TypeError(
            f"Expected subclass of {class_or_tuple}, got {type(cls)} for class {cls}"
        )

map_string_to_enum(string, enum_class)

Map a string to an enum class.

Parameters:

Name Type Description Default
string str

The string to map.

required
enum_class type[Enum]

The enum class to map the string to.

required

Returns:
Any: The corresponding enum value.
Raises:
ValueError: If the string does not match any enum value.

Source code in devices\raspberry_pi_5\src\utils\__init__.py
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
def map_string_to_enum(string: str, enum_class: type[Enum]) -> Any:
    """
    Map a string to an enum class.

    Args:
        string (str): The string to map.
        enum_class (type[Enum]): The enum class to map the string to.
    Returns:
        Any: The corresponding enum value.
    Raises:
        ValueError: If the string does not match any enum value.
    """
    # Check the type of enum_class
    is_subclass(enum_class, Enum)

    try:
        return enum_class[string.upper()]

    except KeyError:
        raise ValueError(
            f"'{string}' is not a valid value for {enum_class.__name__}"
        )

match_any(regex_list, string)

Match any regex pattern in a List.

Parameters:

Name Type Description Default
regex_list List[Pattern]

List of compiled regex patterns.

required
string str

String to match against the regex patterns.

required

Returns:
bool: True if any regex matches the string, False otherwise.

Source code in devices\raspberry_pi_5\src\utils\__init__.py
53
54
55
56
57
58
59
60
61
62
63
def match_any(regex_list: List[Pattern], string: str) -> bool:
    """
    Match any regex pattern in a List.

    Args:
        regex_list (List[Pattern]): List of compiled regex patterns.
        string (str): String to match against the regex patterns.
    Returns:
        bool: True if any regex matches the string, False otherwise.
    """
    return any(regex.match(string) for regex in regex_list)

decorators

ignore_sigint(func)

Decorator to ignore keyboard interrupts (SIGINT) in a function.

Parameters:

Name Type Description Default
func function

The function to decorate.

required

Returns:

Name Type Description
function

The decorated function.

Source code in devices\raspberry_pi_5\src\utils\decorators.py
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
def ignore_sigint(func):
    """
    Decorator to ignore keyboard interrupts (SIGINT) in a function.

    Args:
        func (function): The function to decorate.

    Returns:
        function: The decorated function.
    """

    @wraps(func)
    def wrapper(*args, **kwargs):
        # Ignore the SIGINT signal to prevent the process from being interrupted by Ctrl+C
        signal(SIGINT, SIG_IGN)

        return func(*args, **kwargs)

    return wrapper