|
8 | 8 | TypeVar,
|
9 | 9 | Mapping,
|
10 | 10 | Tuple,
|
| 11 | + get_origin, |
| 12 | + get_type_hints, |
| 13 | + get_args, |
11 | 14 | cast as typing_cast,
|
| 15 | + _GenericAlias, # Remove import and check for Generic in a different way |
12 | 16 | )
|
| 17 | +from inspect import isclass |
13 | 18 |
|
14 | 19 | from dacite.cache import cache
|
15 | 20 |
|
@@ -43,6 +48,16 @@ def is_generic(type_: Type) -> bool:
|
43 | 48 | return hasattr(type_, "__origin__")
|
44 | 49 |
|
45 | 50 |
|
| 51 | +@cache |
| 52 | +def is_generic_subclass(type_: Type) -> bool: |
| 53 | + return is_generic(type_) and hasattr(type_, "__args__") |
| 54 | + |
| 55 | + |
| 56 | +@cache |
| 57 | +def is_generic_alias(type_: Type) -> bool: |
| 58 | + return type(type_.__args__) == _GenericAlias |
| 59 | + |
| 60 | + |
46 | 61 | @cache
|
47 | 62 | def is_union(type_: Type) -> bool:
|
48 | 63 | if is_generic(type_) and type_.__origin__ == Union:
|
@@ -86,6 +101,22 @@ def is_init_var(type_: Type) -> bool:
|
86 | 101 | return isinstance(type_, InitVar) or type_ is InitVar
|
87 | 102 |
|
88 | 103 |
|
| 104 | +def is_valid_generic_class(value: Any, type_: Type) -> bool: |
| 105 | + if not isinstance(value, get_origin(type_)): |
| 106 | + return False |
| 107 | + type_hints = get_type_hints(value) |
| 108 | + for field_name, field_type in type_hints.items(): |
| 109 | + if isinstance(field_type, TypeVar): |
| 110 | + return ( |
| 111 | + any([isinstance(getattr(value, field_name), arg) for arg in get_args(type_)]) |
| 112 | + if get_args(type_) |
| 113 | + else True |
| 114 | + ) |
| 115 | + else: |
| 116 | + return is_instance(value, type_) |
| 117 | + return True |
| 118 | + |
| 119 | + |
89 | 120 | @cache
|
90 | 121 | def extract_init_var(type_: Type) -> Union[Type, Any]:
|
91 | 122 | try:
|
@@ -128,6 +159,17 @@ def is_instance(value: Any, type_: Type) -> bool:
|
128 | 159 | return value in extract_generic(type_)
|
129 | 160 | elif is_init_var(type_):
|
130 | 161 | return is_instance(value, extract_init_var(type_))
|
| 162 | + elif isclass(type(type_)) and type(type_) == _GenericAlias: |
| 163 | + return is_valid_generic_class(value, type_) |
| 164 | + elif isinstance(type_, TypeVar): |
| 165 | + if hasattr(type_, "__constraints__") and type_.__constraints__: |
| 166 | + return any(is_instance(value, t) for t in type_.__constraints__) |
| 167 | + if hasattr(type_, "__bound__") and type_.__bound__: |
| 168 | + if isinstance(type_.__bound__, tuple): |
| 169 | + return any(is_instance(value, t) for t in type_.__bound__) |
| 170 | + if type_.__bound__ is not None and is_generic(type_.__bound__): |
| 171 | + return isinstance(value, type_.__bound__) |
| 172 | + return True |
131 | 173 | elif is_type_generic(type_):
|
132 | 174 | return is_subclass(value, extract_generic(type_)[0])
|
133 | 175 | else:
|
|
0 commit comments