Skip to content

CLN: assorted cleanups, annotations #32475

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 5 commits into from
Mar 7, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
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
2 changes: 1 addition & 1 deletion pandas/_libs/tslibs/timedeltas.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -1167,7 +1167,7 @@ class Timedelta(_Timedelta):

Possible values:

* 'Y', 'M', 'W', 'D', 'T', 'S', 'L', 'U', or 'N'
* 'W', 'D', 'T', 'S', 'L', 'U', or 'N'
* 'days' or 'day'
* 'hours', 'hour', 'hr', or 'h'
* 'minutes', 'minute', 'min', or 'm'
Expand Down
2 changes: 1 addition & 1 deletion pandas/core/arrays/datetimes.py
Original file line number Diff line number Diff line change
Expand Up @@ -988,7 +988,7 @@ def tz_localize(self, tz, ambiguous="raise", nonexistent="raise"):
# ----------------------------------------------------------------
# Conversion Methods - Vectorized analogues of Timestamp methods

def to_pydatetime(self):
def to_pydatetime(self) -> np.ndarray:
"""
Return Datetime Array/Index as object ndarray of datetime.datetime
objects.
Expand Down
2 changes: 1 addition & 1 deletion pandas/core/arrays/timedeltas.py
Original file line number Diff line number Diff line change
Expand Up @@ -825,7 +825,7 @@ def total_seconds(self):
"""
return self._maybe_mask_results(1e-9 * self.asi8, fill_value=None)

def to_pytimedelta(self):
def to_pytimedelta(self) -> np.ndarray:
"""
Return Timedelta Array/Index as object ndarray of datetime.timedelta
objects.
Expand Down
15 changes: 10 additions & 5 deletions pandas/core/indexes/accessors.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
"""
datetimelike delegation
"""
from typing import TYPE_CHECKING

import numpy as np

from pandas.core.dtypes.common import (
Expand All @@ -21,9 +23,12 @@
from pandas.core.indexes.datetimes import DatetimeIndex
from pandas.core.indexes.timedeltas import TimedeltaIndex

if TYPE_CHECKING:
from pandas import Series # noqa:F401


class Properties(PandasDelegate, PandasObject, NoNewAttributesMixin):
def __init__(self, data, orig):
def __init__(self, data: "Series", orig):
if not isinstance(data, ABCSeries):
raise TypeError(
Copy link
Member Author

Choose a reason for hiding this comment

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

@simonjayhawkins does the annotation now make this check unnecessary? not sure if we have a policy for this

f"cannot convert an object of type {type(data)} to a datetimelike index"
Expand Down Expand Up @@ -137,7 +142,7 @@ class DatetimeProperties(Properties):
Raises TypeError if the Series does not contain datetimelike values.
"""

def to_pydatetime(self):
def to_pydatetime(self) -> np.ndarray:
"""
Return the data as an array of native Python datetime objects.

Expand Down Expand Up @@ -209,7 +214,7 @@ class TimedeltaProperties(Properties):
Raises TypeError if the Series does not contain datetimelike values.
"""

def to_pytimedelta(self):
def to_pytimedelta(self) -> np.ndarray:
"""
Return an array of native `datetime.timedelta` objects.

Expand Down Expand Up @@ -271,7 +276,7 @@ def components(self):
2 0 0 0 2 0 0 0
3 0 0 0 3 0 0 0
4 0 0 0 4 0 0 0
""" # noqa: E501
"""
return self._get_values().components.set_index(self._parent.index)

@property
Expand Down Expand Up @@ -303,7 +308,7 @@ class PeriodProperties(Properties):
class CombinedDatetimelikeProperties(
DatetimeProperties, TimedeltaProperties, PeriodProperties
):
def __new__(cls, data):
def __new__(cls, data: "Series"):
# CombinedDatetimelikeProperties isn't really instantiated. Instead
# we need to choose which parent (datetime or timedelta) is
# appropriate. Since we're checking the dtypes anyway, we'll just
Expand Down
2 changes: 1 addition & 1 deletion pandas/core/indexes/range.py
Original file line number Diff line number Diff line change
Expand Up @@ -168,7 +168,7 @@ def _data(self):
return self._cached_data

@cache_readonly
def _int64index(self):
def _int64index(self) -> Int64Index:
return Int64Index._simple_new(self._data, name=self.name)

def _get_data_as_items(self):
Expand Down
6 changes: 3 additions & 3 deletions pandas/core/internals/managers.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,14 +24,14 @@
is_list_like,
is_numeric_v_string_like,
is_scalar,
is_sparse,
)
from pandas.core.dtypes.concat import concat_compat
from pandas.core.dtypes.dtypes import ExtensionDtype
from pandas.core.dtypes.generic import ABCExtensionArray, ABCSeries
from pandas.core.dtypes.missing import isna

import pandas.core.algorithms as algos
from pandas.core.arrays.sparse import SparseDtype
from pandas.core.base import PandasObject
from pandas.core.indexers import maybe_convert_indices
from pandas.core.indexes.api import Index, MultiIndex, ensure_index
Expand Down Expand Up @@ -843,8 +843,8 @@ def _interleave(self) -> np.ndarray:

# TODO: https://github.com/pandas-dev/pandas/issues/22791
# Give EAs some input on what happens here. Sparse needs this.
if is_sparse(dtype):
dtype = dtype.subtype # type: ignore
if isinstance(dtype, SparseDtype):
dtype = dtype.subtype
elif is_extension_array_dtype(dtype):
dtype = "object"

Expand Down
4 changes: 2 additions & 2 deletions pandas/core/nanops.py
Original file line number Diff line number Diff line change
Expand Up @@ -981,7 +981,7 @@ def nanskew(
Examples
--------
>>> import pandas.core.nanops as nanops
>>> s = pd.Series([1,np.nan, 1, 2])
>>> s = pd.Series([1, np.nan, 1, 2])
>>> nanops.nanskew(s)
1.7320508075688787
"""
Expand Down Expand Up @@ -1065,7 +1065,7 @@ def nankurt(
Examples
--------
>>> import pandas.core.nanops as nanops
>>> s = pd.Series([1,np.nan, 1, 3, 2])
>>> s = pd.Series([1, np.nan, 1, 3, 2])
>>> nanops.nankurt(s)
-1.2892561983471076
"""
Expand Down
4 changes: 0 additions & 4 deletions pandas/core/series.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,6 @@
ABCMultiIndex,
ABCPeriodIndex,
ABCSeries,
ABCSparseArray,
)
from pandas.core.dtypes.inference import is_hashable
from pandas.core.dtypes.missing import (
Expand Down Expand Up @@ -289,9 +288,6 @@ def __init__(
pass
elif isinstance(data, (set, frozenset)):
raise TypeError(f"'{type(data).__name__}' type is unordered")
elif isinstance(data, ABCSparseArray):
# handle sparse passed here (and force conversion)
data = data.to_dense()
else:
data = com.maybe_iterable_to_list(data)

Expand Down
2 changes: 1 addition & 1 deletion pandas/tests/frame/indexing/test_datetime.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ def test_set_reset(self):
# set/reset
df = DataFrame({"A": [0, 1, 2]}, index=idx)
result = df.reset_index()
assert result["foo"].dtype, "M8[ns, US/Eastern"
assert result["foo"].dtype == "datetime64[ns, US/Eastern]"

df = result.set_index("foo")
tm.assert_index_equal(df.index, idx)
Expand Down
7 changes: 2 additions & 5 deletions pandas/tseries/frequencies.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
import warnings

import numpy as np
from pytz import AmbiguousTimeError

from pandas._libs.algos import unique_deltas
from pandas._libs.tslibs import Timedelta, Timestamp
Expand Down Expand Up @@ -288,10 +287,7 @@ def infer_freq(index, warn: bool = True) -> Optional[str]:
index = index.values

if not isinstance(index, pd.DatetimeIndex):
try:
index = pd.DatetimeIndex(index)
except AmbiguousTimeError:
index = pd.DatetimeIndex(index.asi8)
index = pd.DatetimeIndex(index)

inferer = _FrequencyInferer(index, warn=warn)
return inferer.get_freq()
Expand Down Expand Up @@ -490,6 +486,7 @@ def _is_business_daily(self) -> bool:
)

def _get_wom_rule(self) -> Optional[str]:
# FIXME: dont leave commented-out
# wdiffs = unique(np.diff(self.index.week))
# We also need -47, -49, -48 to catch index spanning year boundary
# if not lib.ismember(wdiffs, set([4, 5, -47, -49, -48])).all():
Expand Down
1 change: 1 addition & 0 deletions setup.cfg
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,7 @@ exclude_lines =
# Don't complain if non-runnable code isn't run:
if 0:
if __name__ == .__main__.:
if TYPE_CHECKING:

[coverage:html]
directory = coverage_html_report
Expand Down