Open randolf-scholz opened 2 months ago
These constructors can be very simple wrappers, a rough sketch:
def timedelta(value: Any = ..., unit: Optional[str] = None, **kwargs: Any) -> Timedelta:
"""Utility function that ensures that the constructor does not return NaT."""
td = (
Timedelta(unit=unit, **kwargs)
if value is Ellipsis
else Timedelta(value, unit=unit, **kwargs)
)
if isinstance(td, NaTType):
raise ValueError("Constructor returned NaT")
return td
def timestamp(value: Any = ..., **kwargs: Any) -> Timestamp:
"""Utility function that ensures that the constructor does not return NaT."""
ts = Timestamp(**kwargs) if value is Ellipsis else Timestamp(value, **kwargs)
if isinstance(ts, NaTType):
raise ValueError("Constructor returned NaT")
return ts
There’s an issue about introducing a separate NaTD specific to Timedelta. If you did that ( and the same for Period), then NaT could become a Timestamp, and you would get type-safety in the constructors without new constructors
Feature Type
[X] Adding new functionality to pandas
[ ] Changing existing functionality in pandas
[ ] Removing existing functionality in pandas
Problem Description
The default constructors
pd.Timestamp.__new__
andpd.Timedelta.__new__
can returnNaT
, which is a different type. This can lead to silent type errors, depending on the type-checker used. Consider the following example:Type-checking results:
mypy --strict
: No errors (w/ and w/opandas-stubs
)pyright
withuseLibraryCodeForTypes = true
: 4 errors (only formally correct result)pyright
withuseLibraryCodeForTypes = false
: no errorsFeature Description
Introduce new constructors
timestamp
andtimedelta
(in analogy to howpyarrow
does constructors), which are guaranteed to returnpd.Timestamp
andpd.Timedelta
types, or raise an exception in the case whenNaT
is encountered.Alternative Solutions
Split
pd.NaT
into two different types,Timestamp("NaT")
andTimedelta("NaT")
(as is the case innumpy
), which are instances of the respective types. (https://github.com/pandas-dev/pandas/issues/24983)Additional Context