trestle.common.type_utils
trestle.common.type_utils ¤
Utilities for dealing with models.
Attributes¤
logger = logging.getLogger(__name__) module-attribute ¤
Functions:¤
get_inner_type(collection_field_type) ¤
Get the inner model in a generic collection model such as a List or a Dict.
For a dict the return type is of the value and not the key.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
collection_field_type | Union[Type[List[Any]], Type[Dict[str, Any]]] | Provided type annotation from a pydantic object | required |
Returns:
| Type | Description |
|---|---|
Type[Any] | The desired type. |
Source code in trestle/common/type_utils.py
147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 | |
get_origin(field_type) ¤
Generalized and robust get_origin function.
This function is derived from work by pydantic, however, avoids complications from various python versions.
Source code in trestle/common/type_utils.py
46 47 48 49 50 51 52 53 | |
is_collection_field_type(field_type) ¤
Check whether a type hint is a collection type as used by OSCAL.
Specifically this is whether the type is a list or not.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
field_type | Type[Any] | A type or a type alias of a field typically as served via pydantic introspection | required |
Returns:
| Type | Description |
|---|---|
bool | True if it is a collection type list. |
Source code in trestle/common/type_utils.py
119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 | |
is_union_type(origin) ¤
Return True if origin is any form of Union (typing.Union or Python 3.10+ X | Y).
Replaces the fragile string comparison str(origin) == "<class 'types.UnionType'>" with identity checks that are not tied to CPython string internals.
Background
get_origin(Union[A, B])→typing.Union(the special form)get_origin(A | B)→types.UnionType(the class, Python 3.10+)
Source code in trestle/common/type_utils.py
30 31 32 33 34 35 36 37 38 39 40 41 42 43 | |
handler: python