Skip to content

TYP: some more static definitions of methods for DatetimeIndex #36742

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
71 changes: 55 additions & 16 deletions pandas/core/indexes/datetimes.py
Original file line number Diff line number Diff line change
@@ -1,16 +1,17 @@
from datetime import date, datetime, time, timedelta, tzinfo
import functools
import operator
from typing import Optional
from typing import TYPE_CHECKING, Callable, Optional, cast
import warnings

import numpy as np

from pandas._libs import NaT, Period, Timestamp, index as libindex, lib
from pandas._libs.tslibs import Resolution, ints_to_pydatetime, parsing, to_offset
from pandas._libs.tslibs.offsets import prefix_mapping
from pandas._typing import DtypeObj, Label
from pandas._typing import DtypeObj, F, Label
from pandas.errors import InvalidIndexError
from pandas.util._decorators import cache_readonly, doc
from pandas.util._decorators import cache_readonly

from pandas.core.dtypes.common import (
DT64NS_DTYPE,
Expand All @@ -21,6 +22,7 @@
is_integer,
is_scalar,
)
from pandas.core.dtypes.generic import ABCDataFrame
from pandas.core.dtypes.missing import is_valid_nat_for_dtype

from pandas.core.arrays.datetimes import DatetimeArray, tz_to_dtype
Expand All @@ -30,6 +32,29 @@
from pandas.core.indexes.extension import inherit_names
from pandas.core.tools.times import to_time

if TYPE_CHECKING:
from pandas import DataFrame, PeriodIndex, TimedeltaIndex


def dispatch_to_array_and_wrap(delegate) -> Callable[[F], F]:
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

not the final location for this. may do PeriodIndex next and move to share.

duplication with inherit_from_data. different in that inherit_from_data creates a method, whereas this wraps a method.

it maybe that we eventually replace all uses inherit_from_data and therefore can delete rather than deduplicate.

def decorator(func: F) -> F:
name = func.__name__
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Doesn't functools.wraps already copy over the __name__ and __doc__? I think you might be able to reduce the layers of wrapping by one

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this to copy doc from delegate not func.

wraps is to copy name (the code here does not set the name attribute) and the signature for the help/docs

can always add the doc decorator to each method individually and no need for the decorator factory. I did this originally but thought it looked messy with two decorators and repetition.


@functools.wraps(func)
def method_wrapper(self, *args, **kwargs):

result = getattr(self._data, name)(*args, **kwargs)
if isinstance(result, type(self._data)):
return type(self)._simple_new(result, name=self.name)
elif isinstance(result, ABCDataFrame):
return result.set_index(self)
return Index(result, name=self.name)

method_wrapper.__doc__ = getattr(delegate, name).__doc__
return cast(F, method_wrapper)

return decorator


def _new_DatetimeIndex(cls, d):
"""
Expand Down Expand Up @@ -64,8 +89,7 @@ def _new_DatetimeIndex(cls, d):


@inherit_names(
["to_perioddelta", "to_julian_date", "strftime", "isocalendar"]
+ DatetimeArray._field_ops
DatetimeArray._field_ops
+ [
method
for method in DatetimeArray._datetimelike_methods
Expand Down Expand Up @@ -185,6 +209,8 @@ class DatetimeIndex(DatetimeTimedeltaMixin):
ceil
to_period
to_perioddelta
to_julian_date
isocalendar
to_pydatetime
to_series
to_frame
Expand Down Expand Up @@ -220,24 +246,37 @@ class DatetimeIndex(DatetimeTimedeltaMixin):
tz: Optional[tzinfo]

# --------------------------------------------------------------------
# methods that dispatch to array and wrap result in DatetimeIndex
# methods that dispatch to DatetimeArray and wrap result

@dispatch_to_array_and_wrap(DatetimeArray)
def strftime(self, date_format) -> Index:
pass

@doc(DatetimeArray.tz_convert)
@dispatch_to_array_and_wrap(DatetimeArray)
def tz_convert(self, tz) -> "DatetimeIndex":
arr = self._data.tz_convert(tz)
return type(self)._simple_new(arr, name=self.name)
pass

@doc(DatetimeArray.tz_localize)
@dispatch_to_array_and_wrap(DatetimeArray)
def tz_localize(
self, tz, ambiguous="raise", nonexistent="raise"
) -> "DatetimeIndex":
arr = self._data.tz_localize(tz, ambiguous, nonexistent)
return type(self)._simple_new(arr, name=self.name)
pass

@dispatch_to_array_and_wrap(DatetimeArray)
def to_period(self, freq=None) -> "PeriodIndex":
pass

@dispatch_to_array_and_wrap(DatetimeArray)
def to_perioddelta(self, freq) -> "TimedeltaIndex":
pass

@dispatch_to_array_and_wrap(DatetimeArray)
def to_julian_date(self) -> Index:
pass

@doc(DatetimeArray.to_period)
def to_period(self, freq=None) -> "DatetimeIndex":
arr = self._data.to_period(freq)
return type(self)._simple_new(arr, name=self.name)
@dispatch_to_array_and_wrap(DatetimeArray)
def isocalendar(self) -> "DataFrame":
pass
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

i find the 4 line version clearer than the 3 line version

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I am happy with the existing static code, if others are happy with the repetition/duplications


# --------------------------------------------------------------------
# Constructors
Expand Down