type_utils
trestle.common.type_utils
¤
Utilities for dealing with models.
logger
¤
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
def get_inner_type(collection_field_type: Union[Type[List[Any]], Type[Dict[str, Any]]]) -> Type[Any]:
"""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.
Args:
collection_field_type: Provided type annotation from a pydantic object
Returns:
The desired type.
"""
try:
# Pydantic special cases must be dealt with here:
_, _, singular_type = _get_model_field_info(collection_field_type)
if singular_type is not None:
return singular_type
return typing_extensions.get_args(collection_field_type)[-1]
except Exception as e:
logger.debug(e)
raise err.TrestleError('Model type is not a Dict or List') from e
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
def get_origin(field_type: Type[Any]) -> Optional[Type[Any]]:
"""Generalized and robust get_origin function.
This function is derived from work by pydantic, however, avoids complications
from various python versions.
"""
# This executes a fallback that allows a list to be generated from a constrained list.
return typing_extensions.get_origin(field_type) or getattr(field_type, '__origin__', None)
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
def is_collection_field_type(field_type: Type[Any]) -> bool:
"""Check whether a type hint is a collection type as used by OSCAL.
Specifically this is whether the type is a list or not.
Args:
field_type: A type or a type alias of a field typically as served via pydantic introspection
Returns:
True if it is a collection type list.
"""
# first check if it is a pydantic __root__ object
_, root_type, _ = _get_model_field_info(field_type)
if root_type == 'List':
return True
# Retrieves type from a type annotation
origin_type = get_origin(field_type)
return origin_type == list
handler: python