def test_as_type(): assert 10 == as_type(10, int) assert 10 == as_type("10", int) assert 1 == as_type(1.1, int) assert "10" == as_type(10, str) assert not as_type(False, bool) assert not as_type("no", bool) assert as_type("a:int", Class2).s == Class2("a:int").s assert as_type(None, Class2).s == Class2(None).s assert timedelta(days=2) == as_type("2d", timedelta) assert datetime(2019, 5, 18) == as_type("2019-05-18", datetime)
def _to_pyfloat(obj: Any) -> Any: if obj is None or obj != obj: # NaN return None if isinstance(obj, float): return obj obj = as_type(obj, float) return None if obj != obj else obj
def _to_pydatetime(obj: Any) -> Any: if obj is None or obj is pd.NaT: return None if isinstance(obj, pd.Timestamp): return obj.to_pydatetime() if isinstance(obj, datetime): return obj obj = as_type(obj, datetime) return None if obj != obj else obj
def _get_or(self, key: Union[int, str], expected_type: type, throw: bool = True) -> Any: if (isinstance(key, str) and key in self) or isinstance(key, int): return as_type(self[key], expected_type) if throw: raise KeyError(f"{key} not found") return None
def get(self, key: Union[int, str], default: Any) -> Any: # type: ignore """Get value by `key`, and the value must be a subtype of the type of `default` (which can't be None). If the `key` is not found, return `default`. :param key: the key to search :raises NoneArgumentError: if default is None :raises TypeError: if the value can't be converted to the type of `default` :return: the value by `key`, and the value must be a subtype of the type of `default`. If `key` is not found, return `default` """ assert_arg_not_none(default, "default") if (isinstance(key, str) and key in self) or isinstance(key, int): return as_type(self[key], type(default)) return default
def __init__( self, name: str, data_type: Any, nullable: bool, required: bool = True, default_value: Any = None, metadata: Any = None, ): super().__init__(name, data_type, nullable, metadata) self.required = required self.default_value = default_value if required: aot(default_value is None, "required var can't have default_value") elif default_value is None: aot(nullable, "default_value can't be None because it's not nullable") else: self.default_value = as_type(self.default_value, self.data_type)
def _to_pybool(obj: Any) -> Any: if obj is None or obj != obj: # NaN return None if isinstance(obj, bool): return obj return as_type(obj, bool)