def convert_to_int( val: Union[FVal, bytes, str, int, float], accept_only_exact: bool = True, ) -> int: """Try to convert to an int. Either from an FVal or a string. If it's a float and it's not whole (like 42.0) and accept_only_exact is False then raise Raises: ConversionError: If either the given value is not an exact number or its type can not be converted """ if isinstance(val, FVal): return val.to_int(accept_only_exact) if isinstance(val, (bytes, str)): # Since float string are not converted to int we have to first convert # to float and try to convert to int afterwards try: return int(val) except ValueError: # else also try to turn it into a float try: return FVal(val).to_int(exact=accept_only_exact) except ValueError as e: raise ConversionError(f'Could not convert {val!r} to an int') from e if isinstance(val, int): return val if isinstance(val, float): if val.is_integer() or accept_only_exact is False: return int(val) # else raise ConversionError(f'Can not convert {val} which is of type {type(val)} to int.')
def hex_or_bytes_to_int(value: Union[bytes, str]) -> int: """Turns a bytes/HexBytes or a hexstring into an int May raise: - ConversionError if it can't convert a value to an int or if an unexpected type is given. """ if isinstance(value, bytes): int_value = int.from_bytes(value, byteorder='big', signed=False) elif isinstance(value, str): try: int_value = int(value, 16) except ValueError: raise ConversionError( f'Could not convert string "{value}" to an int') else: raise ConversionError( f'Unexpected type {type(value)} given to hex_or_bytes_to_int()') return int_value
def to_int(self, exact: bool) -> int: """ Tries to convert to int, If `exact` is true then it will convert only if it is a whole decimal number; i.e.: if it has got nothing after the decimal point Raises: ConversionError: If exact was True but the FVal is actually not an exact integer. """ if exact and self.num.to_integral_exact() != self.num: raise ConversionError(f'Tried to ask for exact int from {self.num}') return int(self.num)
def hexstr_to_int(value: str) -> int: """Turns a hexstring into an int May raise: - ConversionError if it can't convert a value to an int or if an unexpected type is given. """ try: int_value = int(value, 16) except ValueError as e: raise ConversionError(f'Could not convert string "{value}" to an int') from e return int_value