nat.utils.type_converter#
Attributes#
Exceptions#
Common base class for all non-exit exceptions. |
Classes#
Parameters |
|
Functions#
|
Module Contents#
- logger#
- _T#
- exception ConvertException#
Bases:
ExceptionCommon base class for all non-exit exceptions.
Initialize self. See help(type(self)) for accurate signature.
- class TypeConverter(
- converters: list[collections.abc.Callable[[Any], Any]],
- parent: TypeConverter | None = None,
Parameters#
- converterslist[Callable[[typing.Any], typing.Any]]
A list of single-argument converter callables annotated with their input param and return type.
- parentTypeConverter | None
An optional parent TypeConverter for fallback.
- _global_initialized = False#
- _converters: collections.OrderedDict[type, collections.OrderedDict[type, collections.abc.Callable]]#
- _parent = None#
- add_converter(converter: collections.abc.Callable) None#
Registers a converter. Must have exactly one parameter and an annotated return type.
Parameters#
- converterCallable
A converter function. Must have exactly one parameter and an annotated return type.
Raises#
- ValueError
If the converter does not have a return type or exactly one argument or the argument has no data type.
- _convert(data: Any, to_type: type[_T]) _T | None#
Attempts to convert
dataintoto_type. Returns None if no path is found.
- convert(data: Any, to_type: type[_T]) _T#
Converts or raises ValueError if no conversion path is found. We also give the parent a chance if self fails.
Parameters#
- datatyping.Any
The value to convert.
- to_typetype
The type to convert the value to.
Returns#
- _T
The converted value.
Raises#
- ValueError
If the value cannot be converted to the specified type.
- try_convert(data: Any, to_type: type[_T]) _T | Any#
Converts with graceful error handling. If conversion fails, returns the original data and continues processing.
Parameters#
- datatyping.Any
The value to convert.
- to_typetype
The type to convert the value to.
Returns#
- _T | typing.Any
The converted value, or original value if conversion fails.
- _try_direct_conversion(
- data: Any,
- target_root_type: type,
Tries direct conversion in this converter’s registry. If no match here, we forward to parent’s direct conversion for recursion up the chain.
- _try_indirect_convert(data: Any, to_type: type[_T]) _T | None#
Attempt indirect conversion (DFS) in this converter. If no success, fallback to parent’s indirect attempt.
- class GlobalTypeConverter#
- _global_converter: TypeConverter#
- static get() TypeConverter#
- static register_converter(converter: collections.abc.Callable) None#
- _text_io_wrapper_to_string(data: io.TextIOWrapper) str#