"""Validate and convert values to desired types."""fromcollections.abcimportIterablefromtypingimportTypeVar_T=TypeVar("_T",bool,float,int,None,str)def_validate_id(old_func):defnew_func(new_id:str):ifnew_id.isdigit()andint(new_id)>=0:old_func(new_id)else:msg="ID string must represent a nonnegative integer."raiseValueError(msg)returnnew_func
[docs]defalphanum_key(val:str)->tuple[str,_T]:"""A key for alphanumerically sorting strings. Args: val (str): String representation of object for which to provide key. Raises: TypeError: The type of 'val' is invalid. Returns: Tuple[str, Union[bool, float, int, None, str]]: Key for 'val'. """ifnotisinstance(val,str):msg=(f"Type: {type(val)} not supported. alphanum_key ""only supports arguments of type: str.")raiseTypeError(msg)try:val_key=float(val)type_key="n"exceptValueError:matchval:case"True"|"False":type_key="b"val_key=val=="True"case"None":type_key="N"val_key=Nonecase_:type_key="s"val_key=valreturntype_key,val_key
[docs]defalphanum_sort(vals:Iterable[str])->list[str]:"""Alphanumerically sorts 'vals'. Args: vals (Iterable): Iterable to be sorted Returns: List[str]: Alphanumerically sorted copy of 'vals'. """returnsorted(vals,key=alphanum_key)
[docs]defval_to_native(val:float|int|str|None)->_T:"""Converts string representations of float/int/str to its native type. Args: val (Optional[Union[float, int, str]]): Parameter to be converted. Returns: PRIMITIVE_TYPE: The converted parameter. """try:float_val=float(val)try:int_val=int(val)native_val=int_valifint_val==float_valelsefloat_valexceptValueError:native_val=float_valexcept(ValueError,TypeError):ifval=="True":native_val=Trueelifval=="False":native_val=Falseelifval=="None":native_val=Noneelse:native_val=valreturnnative_val
[docs]defiter_to_native(vals:Iterable[float|int|str|None],)->Iterable[float|int|str|None]:"""Converts elements of an iterable to their native types. Args: vals (Iterable[Optional[float, int, str]]): Iterable to be converted Returns: Iterable: A shallow copy of the converted Iterable. Example: >>> from autojob.coordinator.validation import iter_to_native >>> vals = ["0.1", "None", "-1", "dog"] >>> iter_to_native(vals) [0.1, None, -1, 'dog'] """new_vals=[]constructor=type(vals)forvalinvals:new_vals.append(val_to_native(val))try:returnconstructor(new_vals)except(TypeError,ValueError):returnlist(new_vals)