typing_to_base

privex.helpers.common.typing_to_base(tp, fail=False, return_orig=True, clean_union=True) → Optional[Union[type, object, callable, tuple, Tuple[type]]][source]

Attempt to extract one or more native Python base types from a typing type, including generics such as List[str], and combined types such as Union[list, str]

>>> typing_to_base(List[str])
list
>>> typing_to_base(Union[str, Dict[str, list], int])
(str, dict, int)
>>> typing_to_base(Union[str, Dict[str, list], int], clean_union=False)
(str, typing.Dict[str, list], int)
>>> typing_to_base(str)
str
>>> typing_to_base(str, fail=True)
TypeError: Failed to extract base type for type object: <class 'str'>
>>> repr(typing_to_base(str, return_orig=False))
'None'
Parameters
  • tp – The typing type object to extract base/native type(s) from.

  • fail (bool) – (Default: False) If True, then raises TypeError if tp doesn’t appear to be a typing type.

  • return_orig (bool) – (Default: True) If True, returns tp as-is if it’s not a typing type. When False, non- typing types will cause None to be returned.

  • clean_union (bool) – (Default: True) If True, typing.Union’s will have each type converted/validated into a normal type using extract_type()

Return type_res

Either a type base type, a tuple of types, a typing type object, or something else depending on what type tp was.