| 1 |
# SPDX-License-Identifier: GPL-3.0-or-later |
| 2 |
# Copyright (C) 2025-2026 Benjamin Abendroth <[email protected]> |
| 3 |
|
| 4 |
'''Type utility functions.''' |
| 5 |
|
| 6 |
from types import NoneType |
| 7 |
|
| 8 |
from .errors import CrazyTypeError |
| 9 |
|
| 10 |
|
| 11 |
def is_dict_type(obj): |
| 12 |
'''Return if `obj` is a dictionary type.''' |
| 13 |
|
| 14 |
return hasattr(obj, 'items') |
| 15 |
|
| 16 |
|
| 17 |
def is_list_type(obj): |
| 18 |
'''Return if `obj` is list or tuple.''' |
| 19 |
|
| 20 |
return isinstance(obj, (list, tuple)) |
| 21 |
|
| 22 |
|
| 23 |
def validate_type(value, types, parameter_name): |
| 24 |
'''Check if `value` is one of `types`.''' |
| 25 |
|
| 26 |
if not isinstance(value, types): |
| 27 |
types_strings = [] |
| 28 |
for t in types: |
| 29 |
types_strings.append({ |
| 30 |
str: 'str', |
| 31 |
int: 'int', |
| 32 |
float: 'float', |
| 33 |
list: 'list', |
| 34 |
tuple: 'tuple', |
| 35 |
dict: 'dict', |
| 36 |
bool: 'bool', |
| 37 |
NoneType: 'None'}[t]) |
| 38 |
types_string = '|'.join(types_strings) |
| 39 |
|
| 40 |
raise CrazyTypeError(parameter_name, types_string, value) |