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 is_type_matching(value: Any, type_: Any) -> bool: # Union if hasattr(type_, "__origin__") and type_.__origin__ is Union: types = list(type_.__args__) for idx, t in enumerate(types): # for now treat any Dict[X,Y] as dict and any List[X] as list, ignoring element types if is_dict_annotation(t): t = dict elif is_list_annotation(t): t = list types[idx] = t return isinstance(value, tuple(types)) else: primitives = (int, float, bool, str) if type_ in primitives: return type(value) is type_ if type_ in (Any, inspect.Signature.empty): return True return isinstance(value, type_)
def check_node_metadata( node: Container, type_hint: Any, key_type: Any, elt_type: Any, obj_type: Any, ) -> None: value_optional, value_ref_type = _resolve_optional(type_hint) assert node._metadata.optional == value_optional assert node._metadata.ref_type == value_ref_type assert node._metadata.key_type == key_type assert node._metadata.element_type == elt_type assert node._metadata.object_type == obj_type if is_dict_annotation(value_ref_type) or is_structured_config( value_ref_type): assert isinstance(node, DictConfig) elif is_list_annotation(value_ref_type): assert isinstance(node, ListConfig)
def test_is_list_annotation(type_: Any, expected: Any) -> Any: assert is_list_annotation(type_=type_) == expected