generated from jCloud/repository-template
Add function to assert that an object is an instance of a specific type
This commit is contained in:
@@ -82,4 +82,37 @@ def human_readable_list(ls: list, final_separator: str = 'and', quotation_mark:
|
||||
_quote(str(obj), quotation_mark) # quote the string representation of the object
|
||||
for obj in ls[:-1] # do not include the last element of the list
|
||||
]
|
||||
) + ' ' + final_separator + ' ' + _quote(str(ls[-1]), quotation_mark)
|
||||
) + ' ' + final_separator + ' ' + _quote(str(ls[-1]), quotation_mark)
|
||||
|
||||
def _list_type_names(types: list[type]) -> list[str]:
|
||||
'''
|
||||
Converts a list of types into a list of their names (``__name__``
|
||||
attribute)
|
||||
|
||||
:param types: The list of types
|
||||
:type types: list[type]
|
||||
|
||||
:return: The list of the names of the types
|
||||
:rtype: list[str]
|
||||
'''
|
||||
|
||||
return [tp.__name__ for tp in types]
|
||||
|
||||
def assert_that_is_instance(obj: object, class_or_tuple: Union[type, types.UnionType, tuple[type, ...]]) -> None:
|
||||
if not isinstance(class_or_tuple, Union[type, types.UnionType, tuple]):
|
||||
raise TypeError(f'class_or_tuple: expected \'Union[type, types.UnionType, tuple[type, ...]]\', \'got {type(class_or_tuple).__name__}\'')
|
||||
if not isinstance(obj, class_or_tuple):
|
||||
if isinstance(class_or_tuple, (tuple, types.UnionType)):
|
||||
print('MORE')
|
||||
if isinstance(class_or_tuple, types.UnionType):
|
||||
class_or_tuple = class_or_tuple.__args__
|
||||
print('LIST:', _list_type_names(class_or_tuple))
|
||||
if len(class_or_tuple) > 1:
|
||||
exception_message_expected = 'either '
|
||||
else:
|
||||
exception_message_expected = ''
|
||||
exception_message_expected += human_readable_list(_list_type_names(class_or_tuple), 'or', '\'')
|
||||
else:
|
||||
print('SINGLE')
|
||||
exception_message_expected = '\'' + class_or_tuple.__name__ + '\''
|
||||
raise TypeError(f'expected {exception_message_expected}, got \'{type(obj).__name__}\'')
|
||||
Reference in New Issue
Block a user