Skip to content

TYP: Annotations in core/indexes/ #30390

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 2 commits into from
Dec 21, 2019
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
5 changes: 3 additions & 2 deletions pandas/core/indexers.py
Original file line number Diff line number Diff line change
Expand Up @@ -144,8 +144,9 @@ def validate_indices(indices: np.ndarray, n: int) -> None:
if len(indices):
min_idx = indices.min()
if min_idx < -1:
msg = f"'indices' contains values less than allowed ({min_idx} < -1)"
raise ValueError(msg)
raise ValueError(
f"'indices' contains values less than allowed ({min_idx} < -1)"
)

max_idx = indices.max()
if max_idx >= n:
Expand Down
13 changes: 5 additions & 8 deletions pandas/core/indexes/accessors.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,7 @@ class Properties(PandasDelegate, PandasObject, NoNewAttributesMixin):
def __init__(self, data, orig):
if not isinstance(data, ABCSeries):
raise TypeError(
f"cannot convert an object of type {type(data)} to a "
"datetimelike index"
f"cannot convert an object of type {type(data)} to a datetimelike index"
)

self._parent = data
Expand Down Expand Up @@ -91,9 +90,8 @@ def _delegate_property_get(self, name):

def _delegate_property_set(self, name, value, *args, **kwargs):
raise ValueError(
"modifications to a property of a datetimelike "
"object are not supported. Change values on the "
"original."
"modifications to a property of a datetimelike object are not supported. "
"Change values on the original."
)

def _delegate_method(self, name, *args, **kwargs):
Expand Down Expand Up @@ -222,7 +220,7 @@ def to_pytimedelta(self):

Returns
-------
a : numpy.ndarray
numpy.ndarray
Array of 1D containing data with `datetime.timedelta` type.

See Also
Expand Down Expand Up @@ -314,8 +312,7 @@ def __new__(cls, data):

if not isinstance(data, ABCSeries):
raise TypeError(
f"cannot convert an object of type {type(data)} to a "
"datetimelike index"
f"cannot convert an object of type {type(data)} to a datetimelike index"
)

orig = data if is_categorical_dtype(data) else None
Expand Down
2 changes: 0 additions & 2 deletions pandas/core/indexes/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,6 @@ def _get_combined_index(
-------
Index
"""

# TODO: handle index names!
indexes = _get_distinct_objs(indexes)
if len(indexes) == 0:
Expand Down Expand Up @@ -273,7 +272,6 @@ def get_consensus_names(indexes):
list
A list representing the consensus 'names' found.
"""

# find the non-none names, need to tupleify to make
# the set hashable, then reverse on return
consensus_names = {tuple(i.names) for i in indexes if com.any_not_none(*i.names)}
Expand Down
10 changes: 4 additions & 6 deletions pandas/core/indexes/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -804,11 +804,10 @@ def _assert_take_fillable(
# only fill if we are passing a non-None fill_value
if allow_fill and fill_value is not None:
if (indices < -1).any():
msg = (
raise ValueError(
"When allow_fill=True and fill_value is not None, "
"all indices must be >= -1"
)
raise ValueError(msg)
taken = algos.take(
values, indices, allow_fill=allow_fill, fill_value=na_value
)
Expand Down Expand Up @@ -1324,8 +1323,7 @@ def set_names(self, names, level=None, inplace=False):
raise ValueError("Level must be None for non-MultiIndex")

if level is not None and not is_list_like(level) and is_list_like(names):
msg = "Names must be a string when a single level is provided."
raise TypeError(msg)
raise TypeError("Names must be a string when a single level is provided.")

if not is_list_like(names) and level is None and self.nlevels > 1:
raise TypeError("Must pass list-like as `names`.")
Expand Down Expand Up @@ -1421,8 +1419,8 @@ def _validate_index_level(self, level):
if isinstance(level, int):
if level < 0 and level != -1:
raise IndexError(
f"Too many levels: Index has only 1 level,"
f" {level} is not a valid level number"
"Too many levels: Index has only 1 level, "
f"{level} is not a valid level number"
)
elif level > 0:
raise IndexError(
Expand Down
4 changes: 1 addition & 3 deletions pandas/core/indexes/category.py
Original file line number Diff line number Diff line change
Expand Up @@ -715,9 +715,7 @@ def _convert_list_indexer(self, keyarr, kind=None):
indexer = self.categories.get_indexer(np.asarray(keyarr))
if (indexer == -1).any():
raise KeyError(
"a list-indexer must only "
"include values that are "
"in the categories"
"a list-indexer must only include values that are in the categories"
)

return self.get_indexer(keyarr)
Expand Down
11 changes: 6 additions & 5 deletions pandas/core/indexes/datetimelike.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
Base and utility classes for tseries type pandas objects.
"""
import operator
from typing import Set
from typing import List, Set

import numpy as np

Expand Down Expand Up @@ -73,7 +73,7 @@ def method(self, other):

class DatetimeIndexOpsMixin(ExtensionOpsMixin):
"""
common ops mixin to support a unified interface datetimelike Index
Common ops mixin to support a unified interface datetimelike Index.
"""

_data: ExtensionArray
Expand Down Expand Up @@ -336,7 +336,7 @@ def _convert_tolerance(self, tolerance, target):
raise ValueError("list-like tolerance size must match target index size")
return tolerance

def tolist(self):
def tolist(self) -> List:
"""
Return a list of the underlying data.
"""
Expand Down Expand Up @@ -661,11 +661,12 @@ def _summary(self, name=None):
Parameters
----------
name : str
name to use in the summary representation
Name to use in the summary representation.

Returns
-------
String with a summarized representation of the index
str
Summarized representation of the index.
"""
formatter = self._formatter_func
if len(self) > 0:
Expand Down
55 changes: 38 additions & 17 deletions pandas/core/indexes/datetimes.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,9 +45,10 @@


def _new_DatetimeIndex(cls, d):
""" This is called upon unpickling, rather than the default which doesn't
have arguments and breaks __new__ """

"""
This is called upon unpickling, rather than the default which doesn't
have arguments and breaks __new__
"""
if "data" in d and not isinstance(d["data"], DatetimeIndex):
# Avoid need to verify integrity by calling simple_new directly
data = d.pop("data")
Expand Down Expand Up @@ -100,9 +101,9 @@ class DatetimeIndex(DatetimeIndexOpsMixin, Int64Index, DatetimeDelegateMixin):

Parameters
----------
data : array-like (1-dimensional), optional
data : array-like (1-dimensional), optional
Optional datetime-like data to construct index with.
copy : bool
copy : bool
Make a copy of input ndarray.
freq : str or pandas offset object, optional
One of pandas date offset strings or corresponding objects. The string
Expand Down Expand Up @@ -273,7 +274,7 @@ def __new__(
@classmethod
def _simple_new(cls, values, name=None, freq=None, tz=None, dtype=None):
"""
we require the we have a dtype compat for the values
We require the we have a dtype compat for the values
if we are passed a non-dtype compat, then coerce using the constructor
"""
if isinstance(values, DatetimeArray):
Expand Down Expand Up @@ -345,7 +346,13 @@ def tz(self, value):

@cache_readonly
def _is_dates_only(self) -> bool:
"""Return a boolean if we are only dates (and don't have a timezone)"""
"""
Return a boolean if we are only dates (and don't have a timezone)

Returns
-------
bool
"""
from pandas.io.formats.format import _is_dates_only

return _is_dates_only(self.values) and self.tz is None
Expand All @@ -360,7 +367,9 @@ def __reduce__(self):
return _new_DatetimeIndex, (type(self), d), None

def __setstate__(self, state):
"""Necessary for making this object picklable"""
"""
Necessary for making this object picklable.
"""
if isinstance(state, dict):
super().__setstate__(state)

Expand Down Expand Up @@ -393,7 +402,9 @@ def __setstate__(self, state):
_unpickle_compat = __setstate__

def _convert_for_op(self, value):
""" Convert value to be insertable to ndarray """
"""
Convert value to be insertable to ndarray.
"""
if self._has_same_tz(value):
return _to_M8(value)
raise ValueError("Passed item and index have different timezone")
Expand Down Expand Up @@ -461,7 +472,7 @@ def _union(self, other, sort):

def union_many(self, others):
"""
A bit of a hack to accelerate unioning a collection of indexes
A bit of a hack to accelerate unioning a collection of indexes.
"""
this = self

Expand Down Expand Up @@ -489,7 +500,7 @@ def union_many(self, others):
this._data._dtype = dtype
return this

def _can_fast_union(self, other):
def _can_fast_union(self, other) -> bool:
if not isinstance(other, DatetimeIndex):
return False

Expand Down Expand Up @@ -581,7 +592,7 @@ def intersection(self, other, sort=False):

Returns
-------
y : Index or DatetimeIndex or TimedeltaIndex
Index or DatetimeIndex or TimedeltaIndex
"""
return super().intersection(other, sort=sort)

Expand Down Expand Up @@ -699,7 +710,9 @@ def snap(self, freq="S"):
# we know it conforms; skip check
return DatetimeIndex._simple_new(snapped, name=self.name, tz=self.tz, freq=freq)

def join(self, other, how="left", level=None, return_indexers=False, sort=False):
def join(
self, other, how: str = "left", level=None, return_indexers=False, sort=False
):
"""
See Index.join
"""
Expand Down Expand Up @@ -840,9 +853,8 @@ def _parsed_string_to_bounds(self, reso, parsed):
if parsed.tzinfo is not None:
if self.tz is None:
raise ValueError(
"The index must be timezone aware "
"when indexing with a date string with a "
"UTC offset"
"The index must be timezone aware when indexing "
"with a date string with a UTC offset"
)
start = start.tz_localize(parsed.tzinfo).tz_convert(self.tz)
end = end.tz_localize(parsed.tzinfo).tz_convert(self.tz)
Expand All @@ -851,7 +863,16 @@ def _parsed_string_to_bounds(self, reso, parsed):
end = end.tz_localize(self.tz)
return start, end

def _partial_date_slice(self, reso, parsed, use_lhs=True, use_rhs=True):
def _partial_date_slice(
self, reso: str, parsed, use_lhs: bool = True, use_rhs: bool = True
):
"""
Parameters
----------
reso : str
use_lhs : bool, default True
use_rhs : bool, default True
"""
is_monotonic = self.is_monotonic
if (
is_monotonic
Expand Down
8 changes: 5 additions & 3 deletions pandas/core/indexes/frozen.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ def union(self, other) -> "FrozenList":

Returns
-------
diff : FrozenList
FrozenList
The collection difference between self and other.
"""
if isinstance(other, tuple):
Expand All @@ -53,7 +53,7 @@ def difference(self, other) -> "FrozenList":

Returns
-------
diff : FrozenList
FrozenList
The collection difference between self and other.
"""
other = set(other)
Expand Down Expand Up @@ -92,7 +92,9 @@ def __hash__(self):
return hash(tuple(self))

def _disabled(self, *args, **kwargs):
"""This method will not function because object is immutable."""
"""
This method will not function because object is immutable.
"""
raise TypeError(f"'{type(self).__name__}' does not support mutable operations.")

def __str__(self) -> str:
Expand Down
Loading