Skip to content

Commit 3f0e22f

Browse files
authored
TYP: unit str->TimeUnit (#62707)
1 parent 1f81f47 commit 3f0e22f

File tree

8 files changed

+38
-26
lines changed

8 files changed

+38
-26
lines changed

pandas/core/arrays/datetimelike.py

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -157,6 +157,8 @@
157157
Sequence,
158158
)
159159

160+
from pandas._typing import TimeUnit
161+
160162
from pandas import Index
161163
from pandas.core.arrays import (
162164
DatetimeArray,
@@ -2114,7 +2116,7 @@ def _creso(self) -> int:
21142116
return get_unit_from_dtype(self._ndarray.dtype)
21152117

21162118
@cache_readonly
2117-
def unit(self) -> str:
2119+
def unit(self) -> TimeUnit:
21182120
"""
21192121
The precision unit of the datetime data.
21202122
@@ -2138,11 +2140,11 @@ def unit(self) -> str:
21382140
>>> idx.as_unit("s").unit
21392141
's'
21402142
"""
2141-
# error: Argument 1 to "dtype_to_unit" has incompatible type
2142-
# "ExtensionDtype"; expected "Union[DatetimeTZDtype, dtype[Any]]"
2143-
return dtype_to_unit(self.dtype) # type: ignore[arg-type]
2143+
# error: Incompatible return value type (got "str", expected
2144+
# "Literal['s', 'ms', 'us', 'ns']") [return-value]
2145+
return dtype_to_unit(self.dtype) # type: ignore[return-value,arg-type]
21442146

2145-
def as_unit(self, unit: str, round_ok: bool = True) -> Self:
2147+
def as_unit(self, unit: TimeUnit, round_ok: bool = True) -> Self:
21462148
"""
21472149
Convert to a dtype with the given unit resolution.
21482150

pandas/core/arrays/datetimes.py

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -88,6 +88,7 @@
8888
IntervalClosedType,
8989
TimeAmbiguous,
9090
TimeNonexistent,
91+
TimeUnit,
9192
npt,
9293
)
9394

@@ -394,7 +395,10 @@ def _from_sequence_not_strict(
394395
result = cls._simple_new(subarr, freq=inferred_freq, dtype=data_dtype)
395396
if unit is not None and unit != result.unit:
396397
# If unit was specified in user-passed dtype, cast to it here
397-
result = result.as_unit(unit)
398+
# error: Argument 1 to "as_unit" of "TimelikeOps" has
399+
# incompatible type "str"; expected "Literal['s', 'ms', 'us', 'ns']"
400+
# [arg-type]
401+
result = result.as_unit(unit) # type: ignore[arg-type]
398402

399403
validate_kwds = {"ambiguous": ambiguous}
400404
result._maybe_pin_freq(freq, validate_kwds)
@@ -413,7 +417,7 @@ def _generate_range(
413417
nonexistent: TimeNonexistent = "raise",
414418
inclusive: IntervalClosedType = "both",
415419
*,
416-
unit: str | None = None,
420+
unit: TimeUnit = "ns",
417421
) -> Self:
418422
periods = dtl.validate_periods(periods)
419423
if freq is None and any(x is None for x in [periods, start, end]):
@@ -534,7 +538,7 @@ def _unbox_scalar(self, value) -> np.datetime64:
534538
raise ValueError("'value' should be a Timestamp.")
535539
self._check_compatible_with(value)
536540
if value is NaT:
537-
return np.datetime64(value._value, self.unit) # type: ignore[call-overload]
541+
return np.datetime64(value._value, self.unit)
538542
else:
539543
return value.as_unit(self.unit, round_ok=False).asm8
540544

pandas/core/arrays/period.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -962,7 +962,9 @@ def astype(self, dtype, copy: bool = True):
962962
# GH#45038 match PeriodIndex behavior.
963963
tz = getattr(dtype, "tz", None)
964964
unit = dtl.dtype_to_unit(dtype)
965-
return self.to_timestamp().tz_localize(tz).as_unit(unit)
965+
# error: Argument 1 to "as_unit" of "TimelikeOps" has incompatible
966+
# type "str"; expected "Literal['s', 'ms', 'us', 'ns']" [arg-type]
967+
return self.to_timestamp().tz_localize(tz).as_unit(unit) # type: ignore[arg-type]
966968

967969
return super().astype(dtype, copy=copy)
968970

pandas/core/arrays/timedeltas.py

Lines changed: 5 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -73,6 +73,7 @@
7373
DtypeObj,
7474
NpDtype,
7575
npt,
76+
TimeUnit,
7677
)
7778

7879
from pandas import DataFrame
@@ -275,7 +276,7 @@ def _from_sequence_not_strict(
275276

276277
@classmethod
277278
def _generate_range(
278-
cls, start, end, periods, freq, closed=None, *, unit: str | None = None
279+
cls, start, end, periods, freq, closed=None, *, unit: TimeUnit
279280
) -> Self:
280281
periods = dtl.validate_periods(periods)
281282
if freq is None and any(x is None for x in [periods, start, end]):
@@ -293,11 +294,8 @@ def _generate_range(
293294
if end is not None:
294295
end = Timedelta(end).as_unit("ns")
295296

296-
if unit is not None:
297-
if unit not in ["s", "ms", "us", "ns"]:
298-
raise ValueError("'unit' must be one of 's', 'ms', 'us', 'ns'")
299-
else:
300-
unit = "ns"
297+
if unit not in ["s", "ms", "us", "ns"]:
298+
raise ValueError("'unit' must be one of 's', 'ms', 'us', 'ns'")
301299

302300
if start is not None and unit is not None:
303301
start = start.as_unit(unit, round_ok=False)
@@ -327,7 +325,7 @@ def _unbox_scalar(self, value) -> np.timedelta64:
327325
raise ValueError("'value' should be a Timedelta.")
328326
self._check_compatible_with(value)
329327
if value is NaT:
330-
return np.timedelta64(value._value, self.unit) # type: ignore[call-overload]
328+
return np.timedelta64(value._value, self.unit)
331329
else:
332330
return value.as_unit(self.unit, round_ok=False).asm8
333331

pandas/core/indexes/datetimelike.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -75,6 +75,7 @@
7575
from pandas._typing import (
7676
Axis,
7777
JoinHow,
78+
TimeUnit,
7879
npt,
7980
)
8081

@@ -434,10 +435,10 @@ class DatetimeTimedeltaMixin(DatetimeIndexOpsMixin, ABC):
434435
_is_unique = Index.is_unique
435436

436437
@property
437-
def unit(self) -> str:
438+
def unit(self) -> TimeUnit:
438439
return self._data.unit
439440

440-
def as_unit(self, unit: str) -> Self:
441+
def as_unit(self, unit: TimeUnit) -> Self:
441442
"""
442443
Convert to a dtype with the given unit resolution.
443444

pandas/core/indexes/datetimes.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,7 @@
6666
TimeAmbiguous,
6767
TimeNonexistent,
6868
npt,
69+
TimeUnit,
6970
)
7071

7172
from pandas.core.api import (
@@ -852,7 +853,7 @@ def date_range(
852853
name: Hashable | None = None,
853854
inclusive: IntervalClosedType = "both",
854855
*,
855-
unit: str | None = None,
856+
unit: TimeUnit = "ns",
856857
**kwargs,
857858
) -> DatetimeIndex:
858859
"""
@@ -893,7 +894,7 @@ def date_range(
893894
Include boundaries; Whether to set each bound as closed or open.
894895
895896
.. versionadded:: 1.4.0
896-
unit : str, default None
897+
unit : {'s', 'ms', 'us', 'ns'}, default 'ns'
897898
Specify the desired resolution of the result.
898899
899900
.. versionadded:: 2.0.0

pandas/core/indexes/timedeltas.py

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,10 @@
3333

3434
if TYPE_CHECKING:
3535
from pandas._libs import NaTType
36-
from pandas._typing import DtypeObj
36+
from pandas._typing import (
37+
DtypeObj,
38+
TimeUnit,
39+
)
3740

3841

3942
@inherit_names(
@@ -249,7 +252,7 @@ def timedelta_range(
249252
name=None,
250253
closed=None,
251254
*,
252-
unit: str | None = None,
255+
unit: TimeUnit = "ns",
253256
) -> TimedeltaIndex:
254257
"""
255258
Return a fixed frequency TimedeltaIndex with day as the default.
@@ -269,7 +272,7 @@ def timedelta_range(
269272
closed : str, default None
270273
Make the interval closed with respect to the given frequency to
271274
the 'left', 'right', or both sides (None).
272-
unit : str, default None
275+
unit : {'s', 'ms', 'us', 'ns'}, default 'ns'
273276
Specify the desired resolution of the result.
274277
275278
.. versionadded:: 2.0.0

pandas/core/resample.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -99,6 +99,7 @@
9999
TimedeltaConvertibleTypes,
100100
TimeGrouperOrigin,
101101
TimestampConvertibleTypes,
102+
TimeUnit,
102103
npt,
103104
)
104105

@@ -2835,7 +2836,7 @@ def _get_timestamp_range_edges(
28352836
first: Timestamp,
28362837
last: Timestamp,
28372838
freq: BaseOffset,
2838-
unit: str,
2839+
unit: TimeUnit,
28392840
closed: Literal["right", "left"] = "left",
28402841
origin: TimeGrouperOrigin = "start_day",
28412842
offset: Timedelta | None = None,
@@ -2985,7 +2986,7 @@ def _adjust_dates_anchored(
29852986
closed: Literal["right", "left"] = "right",
29862987
origin: TimeGrouperOrigin = "start_day",
29872988
offset: Timedelta | None = None,
2988-
unit: str = "ns",
2989+
unit: TimeUnit = "ns",
29892990
) -> tuple[Timestamp, Timestamp]:
29902991
# First and last offsets should be calculated from the start day to fix an
29912992
# error cause by resampling across multiple days when a one day period is
@@ -3094,7 +3095,7 @@ def asfreq(
30943095

30953096
new_obj.index = _asfreq_compat(obj.index, freq)
30963097
else:
3097-
unit = None
3098+
unit: TimeUnit = "ns"
30983099
if isinstance(obj.index, DatetimeIndex):
30993100
# TODO: should we disallow non-DatetimeIndex?
31003101
unit = obj.index.unit

0 commit comments

Comments
 (0)