def test_get_key_value_types(key_type: Any, expected_key_type: Any, value_type: Any, expected_value_type: Any) -> None: dt = Dict[key_type, value_type] # type:ignore assert _utils.get_dict_key_value_types(dt) == ( expected_key_type, expected_value_type, )
def test_get_key_value_types( key_type: Any, expected_key_type: Any, value_type: Any, expected_value_type: Any, ) -> None: dt = Dict[key_type, value_type] # type: ignore if expected_key_type is not None and issubclass(expected_key_type, Exception): with pytest.raises(expected_key_type): _utils.get_dict_key_value_types(dt) else: assert _utils.get_dict_key_value_types(dt) == ( expected_key_type, expected_value_type, )
def collect_imports(imports: Set[Any], type_: Any) -> None: if is_list_annotation(type_): collect_imports(imports, get_list_element_type(type_)) type_ = List elif is_dict_annotation(type_): kvt = get_dict_key_value_types(type_) collect_imports(imports, kvt[0]) collect_imports(imports, kvt[1]) type_ = Dict else: is_optional = _resolve_optional(type_)[0] if is_optional and type_ is not Any: type_ = Optional imports.add(type_)
def is_incompatible(type_: Type[Any]) -> bool: opt = _resolve_optional(type_) # Unions are not supported (Except Optional) if not opt[0] and _is_union(type_): return True type_ = opt[1] if type_ in (type(None), tuple, list, dict): return False try: if is_list_annotation(type_): lt = get_list_element_type(type_) return is_incompatible(lt) if is_dict_annotation(type_): kvt = get_dict_key_value_types(type_) if not issubclass(kvt[0], (str, Enum)): return True return is_incompatible(kvt[1]) if is_tuple_annotation(type_): for arg in type_.__args__: if arg is not ... and is_incompatible(arg): return True return False if get_origin(type_) is Callable: args = get_args(type_) for arg in args[0]: if arg is not ... and is_incompatible(arg): return True if is_incompatible(args[1]): return True return False except ValidationError: return True if type_ is Any or issubclass(type_, (int, float, str, bool, Enum)): return False if is_structured_config(type_): try: OmegaConf.structured(type_) # verify it's actually legal except ValidationError as e: log.debug( f"Failed to create DictConfig from ({type_.__name__}) : {e}, flagging as incompatible" ) return True return False return True
def test_get_dict_key_value_types( ref_type: Any, expected_key_type: Any, expected_element_type: Any ) -> None: key_type, element_type = get_dict_key_value_types(ref_type) assert key_type == expected_key_type assert element_type == expected_element_type
def test_get_dict_key_value_types_python_3_10() -> None: if sys.version_info >= (3, 9): # this if-statement is for mypy's benefit key_type, element_type = get_dict_key_value_types(dict[int, float]) assert key_type == int assert element_type == float