Skip to content

CLN: dont return anything from _validate_indexer; annotations #31321

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 7 commits into from
Jan 31, 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
42 changes: 20 additions & 22 deletions pandas/core/indexes/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -3117,7 +3117,8 @@ def _convert_scalar_indexer(self, key, kind=None):
assert kind in ["loc", "getitem", "iloc", None]

if kind == "iloc":
return self._validate_indexer("positional", key, kind)
self._validate_indexer("positional", key, "iloc")
return key

if len(self) and not isinstance(self, ABCMultiIndex):

Expand All @@ -3126,11 +3127,11 @@ def _convert_scalar_indexer(self, key, kind=None):
# or label indexing if we are using a type able
# to be represented in the index

if kind in ["getitem"] and is_float(key):
if kind == "getitem" and is_float(key):
if not self.is_floating():
self._invalid_indexer("label", key)

elif kind in ["loc"] and is_float(key):
elif kind == "loc" and is_float(key):

# we want to raise KeyError on string/mixed here
# technically we *could* raise a TypeError
Expand All @@ -3144,7 +3145,7 @@ def _convert_scalar_indexer(self, key, kind=None):
]:
self._invalid_indexer("label", key)

elif kind in ["loc"] and is_integer(key):
elif kind == "loc" and is_integer(key):
if not self.holds_integer():
self._invalid_indexer("label", key)

Expand All @@ -3170,11 +3171,10 @@ def _convert_slice_indexer(self, key: slice, kind=None):

# validate iloc
if kind == "iloc":
return slice(
self._validate_indexer("slice", key.start, kind),
self._validate_indexer("slice", key.stop, kind),
self._validate_indexer("slice", key.step, kind),
)
self._validate_indexer("slice", key.start, "iloc")
self._validate_indexer("slice", key.stop, "iloc")
self._validate_indexer("slice", key.step, "iloc")
return key

# potentially cast the bounds to integers
start, stop, step = key.start, key.stop, key.step
Expand All @@ -3195,11 +3195,10 @@ def is_int(v):
integers
"""
if self.is_integer() or is_index_slice:
return slice(
self._validate_indexer("slice", key.start, kind),
self._validate_indexer("slice", key.stop, kind),
self._validate_indexer("slice", key.step, kind),
)
self._validate_indexer("slice", key.start, "getitem")
self._validate_indexer("slice", key.stop, "getitem")
self._validate_indexer("slice", key.step, "getitem")
return key

# convert the slice to an indexer here

Expand Down Expand Up @@ -3329,7 +3328,7 @@ def _convert_list_indexer(self, keyarr, kind=None):

return None

def _invalid_indexer(self, form, key):
def _invalid_indexer(self, form: str_t, key):
"""
Consistent invalid indexer message.
"""
Expand Down Expand Up @@ -4987,20 +4986,19 @@ def _maybe_cast_indexer(self, key):
pass
return key

def _validate_indexer(self, form, key, kind: str_t):
def _validate_indexer(self, form: str_t, key, kind: str_t):
"""
If we are positional indexer, validate that we have appropriate
typed bounds must be an integer.
"""
assert kind in ["loc", "getitem", "iloc"]
assert kind in ["getitem", "iloc"]

if key is None:
pass
elif is_integer(key):
pass
elif kind in ["iloc", "getitem"]:
else:
self._invalid_indexer(form, key)
return key

_index_shared_docs[
"_maybe_cast_slice_bound"
Expand All @@ -5025,7 +5023,7 @@ def _validate_indexer(self, form, key, kind: str_t):
"""

@Appender(_index_shared_docs["_maybe_cast_slice_bound"])
def _maybe_cast_slice_bound(self, label, side, kind):
def _maybe_cast_slice_bound(self, label, side: str_t, kind):
assert kind in ["loc", "getitem", None]

# We are a plain index here (sub-class override this method if they
Expand Down Expand Up @@ -5056,7 +5054,7 @@ def _searchsorted_monotonic(self, label, side="left"):

raise ValueError("index must be monotonic increasing or decreasing")

def get_slice_bound(self, label, side, kind) -> int:
def get_slice_bound(self, label, side: str_t, kind) -> int:
"""
Calculate slice bound that corresponds to given label.

Expand Down Expand Up @@ -5241,7 +5239,7 @@ def insert(self, loc: int, item):
idx = np.concatenate((_self[:loc], item, _self[loc:]))
return self._shallow_copy_with_infer(idx)

def drop(self, labels, errors="raise"):
def drop(self, labels, errors: str_t = "raise"):
"""
Make new Index with passed list of labels deleted.

Expand Down
4 changes: 2 additions & 2 deletions pandas/core/indexes/category.py
Original file line number Diff line number Diff line change
Expand Up @@ -851,12 +851,12 @@ def _concat_same_dtype(self, to_concat, name):
result.name = name
return result

def _delegate_property_get(self, name, *args, **kwargs):
def _delegate_property_get(self, name: str, *args, **kwargs):
""" method delegation to the ._values """
prop = getattr(self._values, name)
return prop # no wrapping for now

def _delegate_method(self, name, *args, **kwargs):
def _delegate_method(self, name: str, *args, **kwargs):
""" method delegation to the ._values """
method = getattr(self._values, name)
if "inplace" in kwargs:
Expand Down
8 changes: 4 additions & 4 deletions pandas/core/indexes/datetimes.py
Original file line number Diff line number Diff line change
Expand Up @@ -489,7 +489,7 @@ def snap(self, freq="S"):
dta = DatetimeArray(snapped, dtype=self.dtype)
return DatetimeIndex._simple_new(dta, name=self.name)

def _parsed_string_to_bounds(self, reso, parsed):
def _parsed_string_to_bounds(self, reso: str, parsed: datetime):
"""
Calculate datetime bounds for parsed time string and its resolution.

Expand Down Expand Up @@ -581,7 +581,7 @@ def _parsed_string_to_bounds(self, reso, parsed):
return start, end

def _partial_date_slice(
self, reso: str, parsed, use_lhs: bool = True, use_rhs: bool = True
self, reso: str, parsed: datetime, use_lhs: bool = True, use_rhs: bool = True
):
"""
Parameters
Expand Down Expand Up @@ -698,7 +698,7 @@ def get_loc(self, key, method=None, tolerance=None):

return Index.get_loc(self, key, method, tolerance)

def _maybe_cast_for_get_loc(self, key):
def _maybe_cast_for_get_loc(self, key) -> Timestamp:
# needed to localize naive datetimes
key = Timestamp(key)
if key.tzinfo is None:
Expand All @@ -707,7 +707,7 @@ def _maybe_cast_for_get_loc(self, key):
key = key.tz_convert(self.tz)
return key

def _maybe_cast_slice_bound(self, label, side, kind):
def _maybe_cast_slice_bound(self, label, side: str, kind):
"""
If label is a string, cast it to datetime according to resolution.

Expand Down
4 changes: 2 additions & 2 deletions pandas/core/indexes/extension.py
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,7 @@ def wrapper(cls):
return wrapper


def _make_wrapped_comparison_op(opname):
def _make_wrapped_comparison_op(opname: str):
"""
Create a comparison method that dispatches to ``._data``.
"""
Expand All @@ -127,7 +127,7 @@ def wrapper(self, other):
return wrapper


def make_wrapped_arith_op(opname):
def make_wrapped_arith_op(opname: str):
def method(self, other):
meth = getattr(self._data, opname)
result = meth(_maybe_unwrap_index(other))
Expand Down
5 changes: 3 additions & 2 deletions pandas/core/indexes/interval.py
Original file line number Diff line number Diff line change
Expand Up @@ -216,6 +216,7 @@ class IntervalIndex(IntervalMixin, ExtensionIndex):
# Immutable, so we are able to cache computations like isna in '_mask'
_mask = None

_data: IntervalArray
# --------------------------------------------------------------------
# Constructors

Expand Down Expand Up @@ -394,11 +395,11 @@ def __contains__(self, key: Any) -> bool:
return False

@cache_readonly
def _multiindex(self):
def _multiindex(self) -> MultiIndex:
return MultiIndex.from_arrays([self.left, self.right], names=["left", "right"])

@cache_readonly
def values(self):
def values(self) -> IntervalArray:
"""
Return the IntervalIndex's data as an IntervalArray.
"""
Expand Down
2 changes: 1 addition & 1 deletion pandas/core/indexes/numeric.py
Original file line number Diff line number Diff line change
Expand Up @@ -393,7 +393,7 @@ def _convert_scalar_indexer(self, key, kind=None):
assert kind in ["loc", "getitem", "iloc", None]

if kind == "iloc":
return self._validate_indexer("positional", key, kind)
self._validate_indexer("positional", key, "iloc")

return key

Expand Down
6 changes: 3 additions & 3 deletions pandas/core/indexes/period.py
Original file line number Diff line number Diff line change
Expand Up @@ -383,7 +383,7 @@ def __contains__(self, key: Any) -> bool:
return False

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

# ------------------------------------------------------------------------
Expand Down Expand Up @@ -606,7 +606,7 @@ def get_loc(self, key, method=None, tolerance=None):
except KeyError:
raise KeyError(key)

def _maybe_cast_slice_bound(self, label, side, kind):
def _maybe_cast_slice_bound(self, label, side: str, kind: str):
"""
If label is a string or a datetime, cast it to Period.ordinal according
to resolution.
Expand Down Expand Up @@ -810,7 +810,7 @@ def _union(self, other, sort):

# ------------------------------------------------------------------------

def _apply_meta(self, rawarr):
def _apply_meta(self, rawarr) -> "PeriodIndex":
if not isinstance(rawarr, PeriodIndex):
if not isinstance(rawarr, PeriodArray):
rawarr = PeriodArray(rawarr, freq=self.freq)
Expand Down
10 changes: 5 additions & 5 deletions pandas/core/indexes/range.py
Original file line number Diff line number Diff line change
Expand Up @@ -400,7 +400,7 @@ def copy(self, name=None, deep=False, dtype=None, **kwargs):
name = self.name
return self.from_range(self._range, name=name)

def _minmax(self, meth):
def _minmax(self, meth: str):
no_steps = len(self) - 1
if no_steps == -1:
return np.nan
Expand All @@ -409,13 +409,13 @@ def _minmax(self, meth):

return self.start + self.step * no_steps

def min(self, axis=None, skipna=True, *args, **kwargs):
def min(self, axis=None, skipna=True, *args, **kwargs) -> int:
"""The minimum value of the RangeIndex"""
nv.validate_minmax_axis(axis)
nv.validate_min(args, kwargs)
return self._minmax("min")

def max(self, axis=None, skipna=True, *args, **kwargs):
def max(self, axis=None, skipna=True, *args, **kwargs) -> int:
"""The maximum value of the RangeIndex"""
nv.validate_minmax_axis(axis)
nv.validate_max(args, kwargs)
Expand Down Expand Up @@ -519,12 +519,12 @@ def intersection(self, other, sort=False):
new_index = new_index.sort_values()
return new_index

def _min_fitting_element(self, lower_limit):
def _min_fitting_element(self, lower_limit: int) -> int:
"""Returns the smallest element greater than or equal to the limit"""
no_steps = -(-(lower_limit - self.start) // abs(self.step))
return self.start + abs(self.step) * no_steps

def _max_fitting_element(self, upper_limit):
def _max_fitting_element(self, upper_limit: int) -> int:
"""Returns the largest element smaller than or equal to the limit"""
no_steps = (upper_limit - self.start) // abs(self.step)
return self.start + abs(self.step) * no_steps
Expand Down
2 changes: 1 addition & 1 deletion pandas/core/indexes/timedeltas.py
Original file line number Diff line number Diff line change
Expand Up @@ -277,7 +277,7 @@ def get_loc(self, key, method=None, tolerance=None):

return Index.get_loc(self, key, method, tolerance)

def _maybe_cast_slice_bound(self, label, side, kind):
def _maybe_cast_slice_bound(self, label, side: str, kind):
"""
If label is a string, cast it to timedelta according to resolution.

Expand Down