Skip to content

Commit 477b2d5

Browse files
ShaharNavehjbrockmendel
authored andcommitted
TYP: Annotations in core/indexes/ (#30390)
* TYP * Update multi.py
1 parent c869255 commit 477b2d5

File tree

12 files changed

+175
-123
lines changed

12 files changed

+175
-123
lines changed

pandas/core/indexers.py

+3-2
Original file line numberDiff line numberDiff line change
@@ -144,8 +144,9 @@ def validate_indices(indices: np.ndarray, n: int) -> None:
144144
if len(indices):
145145
min_idx = indices.min()
146146
if min_idx < -1:
147-
msg = f"'indices' contains values less than allowed ({min_idx} < -1)"
148-
raise ValueError(msg)
147+
raise ValueError(
148+
f"'indices' contains values less than allowed ({min_idx} < -1)"
149+
)
149150

150151
max_idx = indices.max()
151152
if max_idx >= n:

pandas/core/indexes/accessors.py

+5-8
Original file line numberDiff line numberDiff line change
@@ -26,8 +26,7 @@ class Properties(PandasDelegate, PandasObject, NoNewAttributesMixin):
2626
def __init__(self, data, orig):
2727
if not isinstance(data, ABCSeries):
2828
raise TypeError(
29-
f"cannot convert an object of type {type(data)} to a "
30-
"datetimelike index"
29+
f"cannot convert an object of type {type(data)} to a datetimelike index"
3130
)
3231

3332
self._parent = data
@@ -91,9 +90,8 @@ def _delegate_property_get(self, name):
9190

9291
def _delegate_property_set(self, name, value, *args, **kwargs):
9392
raise ValueError(
94-
"modifications to a property of a datetimelike "
95-
"object are not supported. Change values on the "
96-
"original."
93+
"modifications to a property of a datetimelike object are not supported. "
94+
"Change values on the original."
9795
)
9896

9997
def _delegate_method(self, name, *args, **kwargs):
@@ -222,7 +220,7 @@ def to_pytimedelta(self):
222220
223221
Returns
224222
-------
225-
a : numpy.ndarray
223+
numpy.ndarray
226224
Array of 1D containing data with `datetime.timedelta` type.
227225
228226
See Also
@@ -314,8 +312,7 @@ def __new__(cls, data):
314312

315313
if not isinstance(data, ABCSeries):
316314
raise TypeError(
317-
f"cannot convert an object of type {type(data)} to a "
318-
"datetimelike index"
315+
f"cannot convert an object of type {type(data)} to a datetimelike index"
319316
)
320317

321318
orig = data if is_categorical_dtype(data) else None

pandas/core/indexes/api.py

-2
Original file line numberDiff line numberDiff line change
@@ -124,7 +124,6 @@ def _get_combined_index(
124124
-------
125125
Index
126126
"""
127-
128127
# TODO: handle index names!
129128
indexes = _get_distinct_objs(indexes)
130129
if len(indexes) == 0:
@@ -273,7 +272,6 @@ def get_consensus_names(indexes):
273272
list
274273
A list representing the consensus 'names' found.
275274
"""
276-
277275
# find the non-none names, need to tupleify to make
278276
# the set hashable, then reverse on return
279277
consensus_names = {tuple(i.names) for i in indexes if com.any_not_none(*i.names)}

pandas/core/indexes/base.py

+4-6
Original file line numberDiff line numberDiff line change
@@ -804,11 +804,10 @@ def _assert_take_fillable(
804804
# only fill if we are passing a non-None fill_value
805805
if allow_fill and fill_value is not None:
806806
if (indices < -1).any():
807-
msg = (
807+
raise ValueError(
808808
"When allow_fill=True and fill_value is not None, "
809809
"all indices must be >= -1"
810810
)
811-
raise ValueError(msg)
812811
taken = algos.take(
813812
values, indices, allow_fill=allow_fill, fill_value=na_value
814813
)
@@ -1324,8 +1323,7 @@ def set_names(self, names, level=None, inplace=False):
13241323
raise ValueError("Level must be None for non-MultiIndex")
13251324

13261325
if level is not None and not is_list_like(level) and is_list_like(names):
1327-
msg = "Names must be a string when a single level is provided."
1328-
raise TypeError(msg)
1326+
raise TypeError("Names must be a string when a single level is provided.")
13291327

13301328
if not is_list_like(names) and level is None and self.nlevels > 1:
13311329
raise TypeError("Must pass list-like as `names`.")
@@ -1421,8 +1419,8 @@ def _validate_index_level(self, level):
14211419
if isinstance(level, int):
14221420
if level < 0 and level != -1:
14231421
raise IndexError(
1424-
f"Too many levels: Index has only 1 level,"
1425-
f" {level} is not a valid level number"
1422+
"Too many levels: Index has only 1 level, "
1423+
f"{level} is not a valid level number"
14261424
)
14271425
elif level > 0:
14281426
raise IndexError(

pandas/core/indexes/category.py

+1-3
Original file line numberDiff line numberDiff line change
@@ -715,9 +715,7 @@ def _convert_list_indexer(self, keyarr, kind=None):
715715
indexer = self.categories.get_indexer(np.asarray(keyarr))
716716
if (indexer == -1).any():
717717
raise KeyError(
718-
"a list-indexer must only "
719-
"include values that are "
720-
"in the categories"
718+
"a list-indexer must only include values that are in the categories"
721719
)
722720

723721
return self.get_indexer(keyarr)

pandas/core/indexes/datetimelike.py

+6-5
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
Base and utility classes for tseries type pandas objects.
33
"""
44
import operator
5-
from typing import Set
5+
from typing import List, Set
66

77
import numpy as np
88

@@ -73,7 +73,7 @@ def method(self, other):
7373

7474
class DatetimeIndexOpsMixin(ExtensionOpsMixin):
7575
"""
76-
common ops mixin to support a unified interface datetimelike Index
76+
Common ops mixin to support a unified interface datetimelike Index.
7777
"""
7878

7979
_data: ExtensionArray
@@ -336,7 +336,7 @@ def _convert_tolerance(self, tolerance, target):
336336
raise ValueError("list-like tolerance size must match target index size")
337337
return tolerance
338338

339-
def tolist(self):
339+
def tolist(self) -> List:
340340
"""
341341
Return a list of the underlying data.
342342
"""
@@ -661,11 +661,12 @@ def _summary(self, name=None):
661661
Parameters
662662
----------
663663
name : str
664-
name to use in the summary representation
664+
Name to use in the summary representation.
665665
666666
Returns
667667
-------
668-
String with a summarized representation of the index
668+
str
669+
Summarized representation of the index.
669670
"""
670671
formatter = self._formatter_func
671672
if len(self) > 0:

pandas/core/indexes/datetimes.py

+38-17
Original file line numberDiff line numberDiff line change
@@ -45,9 +45,10 @@
4545

4646

4747
def _new_DatetimeIndex(cls, d):
48-
""" This is called upon unpickling, rather than the default which doesn't
49-
have arguments and breaks __new__ """
50-
48+
"""
49+
This is called upon unpickling, rather than the default which doesn't
50+
have arguments and breaks __new__
51+
"""
5152
if "data" in d and not isinstance(d["data"], DatetimeIndex):
5253
# Avoid need to verify integrity by calling simple_new directly
5354
data = d.pop("data")
@@ -100,9 +101,9 @@ class DatetimeIndex(DatetimeIndexOpsMixin, Int64Index, DatetimeDelegateMixin):
100101
101102
Parameters
102103
----------
103-
data : array-like (1-dimensional), optional
104+
data : array-like (1-dimensional), optional
104105
Optional datetime-like data to construct index with.
105-
copy : bool
106+
copy : bool
106107
Make a copy of input ndarray.
107108
freq : str or pandas offset object, optional
108109
One of pandas date offset strings or corresponding objects. The string
@@ -273,7 +274,7 @@ def __new__(
273274
@classmethod
274275
def _simple_new(cls, values, name=None, freq=None, tz=None, dtype=None):
275276
"""
276-
we require the we have a dtype compat for the values
277+
We require the we have a dtype compat for the values
277278
if we are passed a non-dtype compat, then coerce using the constructor
278279
"""
279280
if isinstance(values, DatetimeArray):
@@ -345,7 +346,13 @@ def tz(self, value):
345346

346347
@cache_readonly
347348
def _is_dates_only(self) -> bool:
348-
"""Return a boolean if we are only dates (and don't have a timezone)"""
349+
"""
350+
Return a boolean if we are only dates (and don't have a timezone)
351+
352+
Returns
353+
-------
354+
bool
355+
"""
349356
from pandas.io.formats.format import _is_dates_only
350357

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

362369
def __setstate__(self, state):
363-
"""Necessary for making this object picklable"""
370+
"""
371+
Necessary for making this object picklable.
372+
"""
364373
if isinstance(state, dict):
365374
super().__setstate__(state)
366375

@@ -393,7 +402,9 @@ def __setstate__(self, state):
393402
_unpickle_compat = __setstate__
394403

395404
def _convert_for_op(self, value):
396-
""" Convert value to be insertable to ndarray """
405+
"""
406+
Convert value to be insertable to ndarray.
407+
"""
397408
if self._has_same_tz(value):
398409
return _to_M8(value)
399410
raise ValueError("Passed item and index have different timezone")
@@ -461,7 +472,7 @@ def _union(self, other, sort):
461472

462473
def union_many(self, others):
463474
"""
464-
A bit of a hack to accelerate unioning a collection of indexes
475+
A bit of a hack to accelerate unioning a collection of indexes.
465476
"""
466477
this = self
467478

@@ -489,7 +500,7 @@ def union_many(self, others):
489500
this._data._dtype = dtype
490501
return this
491502

492-
def _can_fast_union(self, other):
503+
def _can_fast_union(self, other) -> bool:
493504
if not isinstance(other, DatetimeIndex):
494505
return False
495506

@@ -581,7 +592,7 @@ def intersection(self, other, sort=False):
581592
582593
Returns
583594
-------
584-
y : Index or DatetimeIndex or TimedeltaIndex
595+
Index or DatetimeIndex or TimedeltaIndex
585596
"""
586597
return super().intersection(other, sort=sort)
587598

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

702-
def join(self, other, how="left", level=None, return_indexers=False, sort=False):
713+
def join(
714+
self, other, how: str = "left", level=None, return_indexers=False, sort=False
715+
):
703716
"""
704717
See Index.join
705718
"""
@@ -840,9 +853,8 @@ def _parsed_string_to_bounds(self, reso, parsed):
840853
if parsed.tzinfo is not None:
841854
if self.tz is None:
842855
raise ValueError(
843-
"The index must be timezone aware "
844-
"when indexing with a date string with a "
845-
"UTC offset"
856+
"The index must be timezone aware when indexing "
857+
"with a date string with a UTC offset"
846858
)
847859
start = start.tz_localize(parsed.tzinfo).tz_convert(self.tz)
848860
end = end.tz_localize(parsed.tzinfo).tz_convert(self.tz)
@@ -851,7 +863,16 @@ def _parsed_string_to_bounds(self, reso, parsed):
851863
end = end.tz_localize(self.tz)
852864
return start, end
853865

854-
def _partial_date_slice(self, reso, parsed, use_lhs=True, use_rhs=True):
866+
def _partial_date_slice(
867+
self, reso: str, parsed, use_lhs: bool = True, use_rhs: bool = True
868+
):
869+
"""
870+
Parameters
871+
----------
872+
reso : str
873+
use_lhs : bool, default True
874+
use_rhs : bool, default True
875+
"""
855876
is_monotonic = self.is_monotonic
856877
if (
857878
is_monotonic

pandas/core/indexes/frozen.py

+5-3
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@ def union(self, other) -> "FrozenList":
3535
3636
Returns
3737
-------
38-
diff : FrozenList
38+
FrozenList
3939
The collection difference between self and other.
4040
"""
4141
if isinstance(other, tuple):
@@ -53,7 +53,7 @@ def difference(self, other) -> "FrozenList":
5353
5454
Returns
5555
-------
56-
diff : FrozenList
56+
FrozenList
5757
The collection difference between self and other.
5858
"""
5959
other = set(other)
@@ -92,7 +92,9 @@ def __hash__(self):
9292
return hash(tuple(self))
9393

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

98100
def __str__(self) -> str:

0 commit comments

Comments
 (0)