Check if an object is an instance of a type hint, e.g.
to check whether x is of type List[ToolMessage]
or type int
Source code in langroid/utils/types.py
| def is_instance_of(obj: Any, type_hint: Type[T] | Any) -> bool:
"""
Check if an object is an instance of a type hint, e.g.
to check whether x is of type `List[ToolMessage]` or type `int`
"""
if type_hint == Any:
return True
if type_hint is type(obj):
return True
origin = get_origin(type_hint)
args = get_args(type_hint)
if origin is Union:
return any(is_instance_of(obj, arg) for arg in args)
if origin: # e.g. List, Dict, Tuple, Set
if isinstance(obj, origin):
# check if all items in obj are of the required types
if args:
if isinstance(obj, (list, tuple, set)):
return all(is_instance_of(item, args[0]) for item in obj)
if isinstance(obj, dict):
return all(
is_instance_of(k, args[0]) and is_instance_of(v, args[1])
for k, v in obj.items()
)
return True
else:
return False
return isinstance(obj, type_hint)
|