Upload type_utils.py with huggingface_hub
Browse files2 unmodified lines3456782 unmodified linesimport itertoolsimport typingdef isoftype(object, type):"""Checks if an object is of a certain typing type, including nested types.2 unmodified lines34567891011121314151617181920212223242526272829303132333435363738394041424344454647482 unmodified linesimport itertoolsimport typingfrom .utils import safe_evaldef parse_type_string(type_string: str) -> typing.Any:"""Parses a string representing a Python type hint and evaluates it to return the corresponding type object.This function uses a safe evaluation contextto mitigate the risks of executing arbitrary code.Args:type_string (str): A string representation of a Python type hint. Examples include'List[int]', 'Dict[str, Any]', 'Optional[List[str]]', etc.Returns:typing.Any: The Python type object corresponding to the given type string.Raises:ValueError: If the type string contains elements not allowed in the safe contextor tokens list.The function uses a predefined safe context with common types from the `typing` moduleand basic Python data types. It also defines a list of safe tokens that are allowedin the type string."""safe_context = {"Any": typing.Any,"List": typing.List,"Dict": typing.Dict,"Tuple": typing.Tuple,"Union": typing.Union,"int": int,"str": str,"float": float,"bool": bool,"Optional": typing.Optional,}safe_tokens = ["[", "]", ",", " "]return safe_eval(type_string, safe_context, safe_tokens)def isoftype(object, type):"""Checks if an object is of a certain typing type, including nested types.
type_utils.py+40