Source code for primitive_type.converter

"""A quick and simple converter to convert the type of an object."""

import re

from beartype import beartype
from primitive_type.types import Primitive


[docs] class ConvertError(TypeError): """An exception should happens when conversion failed.""" pass
[docs] @beartype def get_primitive_object( val: Primitive, obj_type: type[Primitive] = None ) -> Primitive: """Get a primitive object from a given value. :param val: The given value wants to be converted. :param obj_type: The target type of object that finally converted out. Default to :obj:`None` as disabled. :return: * :class:`str` -- If given value is a normal string, or convert to if type specified. * :class:`int` -- The origin object or convert to. * :class:`float` -- The origin object or convert to. * :class:`bool` -- The origin object or convert to. * :obj:`None` -- Only when given value is :obj:`None`. """ obj_type_required: bool = obj_type is not None if val is None: if obj_type_required: raise TypeError( "Given value is None, could not convert to other type!" ) return None if not obj_type_required: if not isinstance(val, str): return val val_lower = val.lower() if val_lower == "true": return True if val_lower == "false": return False if re.fullmatch(r"[+-]?\d+", val): return int(val) if re.fullmatch(r"[+-]?(\d+(\.\d*)?|\.\d+)([eE][+-]?\d+)?", val): return float(val) return val try: if obj_type is str: return str(val) if obj_type is bool: if isinstance(val, str): return val.lower() == "true" if isinstance(val, (int, float)): return val > 0 return bool(val) if obj_type is int: return int(float(val)) if isinstance(val, str) else int(val) if obj_type is float: return float(val) except (ValueError, TypeError, SyntaxError): raise ConvertError(f"Could not convert '{val}' to type '{obj_type}'.") return val
[docs] def get_str_object(val: Primitive) -> str: """Get a string object from a given value. :param val: The given value wants to be converted. :return: A string object. """ return get_primitive_object(val, str) # ty: ignore[invalid-return-type]
[docs] def get_int_object(val: Primitive) -> int: """Get an integer object from a given value. :param val: The given value wants to be converted. :return: An integer object. """ return get_primitive_object(val, int) # ty: ignore[invalid-return-type]
[docs] def get_float_object(val: Primitive) -> float: """Get a float object from a given value. :param val: The given value wants to be converted. :return: A float object. """ return get_primitive_object(val, float) # ty: ignore[invalid-return-type]
[docs] def get_bool_object(val: Primitive) -> bool: """Get a boolean object from a given value. :param val: The given value wants to be converted. :return: A bool object. """ return get_primitive_object(val, bool) # ty: ignore[invalid-return-type]