def test_get_origin(self): self.assertEqual(list, get_origin(List[int])) self.assertEqual(tuple, get_origin(Tuple[int, ...])) self.assertEqual(dict, get_origin(Dict[str, int])) self.assertEqual(set, get_origin(TypingSet)) self.assertEqual(deque, get_origin(Deque)) self.assertEqual(defaultdict, get_origin(DefaultDict)) self.assertEqual(type, get_origin(Type[int])) self.assertEqual(Set, get_origin(AbstractSet)) self.assertIn('test_origin_and_alias', str(get_origin(Union)))
def is_optional_type(cls: type) -> bool: """ Return True if the given class is an optional type. A type is considered to be optional if it allows ``None`` as value. Example: is_optional_type(Optional[str]) # True is_optional_type(Union[str, int, None]) # True is_optional_type(str) # False is_optional_type(Union[str, int]) # False :param cls: a type. :return: True if cls is an optional type. """ origin = get_origin(cls) args = get_args(cls) return origin == typing.Union and NoneType in args
def default_mapping_deserializer(obj: dict, cls: type, **kwargs) -> Mapping: """ Deserialize a (JSON) dict into a mapping by deserializing all items of that dict. :param obj: the dict that needs deserializing. :param cls: the type, optionally with a generic (e.g. Set[str]). :param kwargs: any keyword arguments. :return: a deserialized set instance. """ cls_ = Mapping cls_args = get_args(cls) if cls_args: cls_ = MappingType[cls_args] dict_ = default_dict_deserializer(obj, cls_, **kwargs) result = dict_ # Strip any generics from cls to allow for an instance check. if not isinstance(result, get_origin(cls)): result = cls(dict_) return result