def __bool__(self, by_content_only=False): if self.value.lower() in self.boolean_texts: return (self.value.lower() == 'true') if by_content_only: raise xlerrors.ValueExcelError( f'Could not convert {repr(self.value)} to bool.') return bool(self.value)
def cast(cls, value): if isinstance(value, cls): return value if not isinstance(value, ExcelType): if type(value) not in NATIVE_TO_XLTYPE: raise xlerrors.ValueExcelError( f'Unknown object type: {type(value)} ({value})') value = NATIVE_TO_XLTYPE[type(value)](value) return getattr(value, f'__{cls.__name__}__')()
def __datetime__(self): try: return utils.number_to_datetime(float(self.value)) except (ValueError, OverflowError): pass try: return dateutil.parser.parse(self.value) except (ValueError, OverflowError): pass raise xlerrors.ValueExcelError( f'Could not cast {repr(self.value)} (of type {type(self.value)} ' f'to date/time.')
def __number__(self): try: return int(self.value) except ValueError: pass try: return float(self.value) except ValueError: pass # For arithmetic, boolean text is actually interpreted. try: return int(self.__bool__(by_content_only=True)) except xlerrors.ValueExcelError: pass # Try casting to datetime first, since the string might represent one # and that can be concerted. try: return utils.datetime_to_number(self.__datetime__()) except xlerrors.ValueExcelError: pass raise xlerrors.ValueExcelError( f'Could not convert {repr(self.value)} to float.')
def __init__(self, data, *args, **kw): try: super().__init__(_convert_nested_list(data), *args, **kw) except ValueError: raise xlerrors.ValueExcelError(f'Invalid array argument: {data}')
def __or__(self, other): if isinstance(other, self.native_types + (Blank, )): raise xlerrors.ValueExcelError('Cannot OR two blank values.') return Boolean.cast(other)
def __float__(self): try: return float(self.value) except (TypeError, ValueError): raise xlerrors.ValueExcelError( f'Could not convert {repr(self.value)} to float.')
def __int__(self): try: return int(float(self.value)) except ValueError: raise xlerrors.ValueExcelError( f'Could not convert {repr(self.value)} to int.')
def test_error(self): err = xlerrors.ValueExcelError('Error') self.assertEqual(str(err), xlerrors.ERROR_CODE_VALUE)