[docs]defalphanum_key(val:str)->tuple[str,PRIMITIVE_TYPE]:"""Provides key to alphanumerically sort primitive types. Args: val: String representation of object for which to provide key. Raises: TypeError: The type of 'val' is invalid. Returns: A 2-tuple where the first element is a string indicating the type of the value (e.g., n = number, b = boolean, N = None, s = string) and the second element is the value. Note: Numbers are converted to floats. """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 an iterable of strings. Args: vals: an iterable to be sorted. Returns: Alphanumerically sorted copy of ``vals``. """returnsorted(vals,key=alphanum_key)
[docs]defval_to_native(val:float|int|str|None)->PRIMITIVE_TYPE:"""Converts string representations to their native types. Only floats, ints, or strings are supported. Args: val: a value to be converted. Returns: The value converted into a :attr:`PRIMITIVE_TYPE`. """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 values within an Iterable to their native types. Args: vals: an iterable of values to convert. Returns: Iterable: A shallow copy of the converted iterable. Example: >>> from autojob.utils import iter_to_native >>> iter_to_native(["0.1", "None", "-1", "dog"]) [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)