Skip to content

Commit

Permalink
REF/TYP: Rename ABCIndexClass->ABCIndex and use cast (pandas-dev#38329)
Browse files Browse the repository at this point in the history
  • Loading branch information
rhshadrach authored and luckyvs1 committed Jan 20, 2021
1 parent 6f6f39f commit 466b855
Show file tree
Hide file tree
Showing 30 changed files with 111 additions and 125 deletions.
16 changes: 9 additions & 7 deletions pandas/core/algorithms.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@
from pandas.core.dtypes.generic import (
ABCDatetimeArray,
ABCExtensionArray,
ABCIndexClass,
ABCIndex,
ABCMultiIndex,
ABCRangeIndex,
ABCSeries,
Expand All @@ -63,6 +63,7 @@

if TYPE_CHECKING:
from pandas import Categorical, DataFrame, Index, Series
from pandas.core.arrays import DatetimeArray, TimedeltaArray

_shared_docs: Dict[str, str] = {}

Expand Down Expand Up @@ -215,7 +216,7 @@ def _reconstruct_data(
values = values.astype(dtype, copy=False)

# we only support object dtypes bool Index
if isinstance(original, ABCIndexClass):
if isinstance(original, ABCIndex):
values = values.astype(object, copy=False)
elif dtype is not None:
if is_datetime64_dtype(dtype):
Expand Down Expand Up @@ -437,9 +438,7 @@ def isin(comps: AnyArrayLike, values: AnyArrayLike) -> np.ndarray:
f"to isin(), you passed a [{type(values).__name__}]"
)

if not isinstance(
values, (ABCIndexClass, ABCSeries, ABCExtensionArray, np.ndarray)
):
if not isinstance(values, (ABCIndex, ABCSeries, ABCExtensionArray, np.ndarray)):
values = _ensure_arraylike(list(values))
elif isinstance(values, ABCMultiIndex):
# Avoid raising in extract_array
Expand Down Expand Up @@ -700,7 +699,7 @@ def factorize(
and values.freq is not None
):
codes, uniques = values.factorize(sort=sort)
if isinstance(original, ABCIndexClass):
if isinstance(original, ABCIndex):
uniques = original._shallow_copy(uniques, name=None)
elif isinstance(original, ABCSeries):
from pandas import Index
Expand Down Expand Up @@ -739,8 +738,11 @@ def factorize(
uniques = _reconstruct_data(uniques, dtype, original)

# return original tenor
if isinstance(original, ABCIndexClass):
if isinstance(original, ABCIndex):
if original.dtype.kind in ["m", "M"] and isinstance(uniques, np.ndarray):
original._data = cast(
"Union[DatetimeArray, TimedeltaArray]", original._data
)
uniques = type(original._data)._simple_new(uniques, dtype=original.dtype)
uniques = original._shallow_copy(uniques, name=None)
elif isinstance(original, ABCSeries):
Expand Down
4 changes: 2 additions & 2 deletions pandas/core/arrays/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@
pandas_dtype,
)
from pandas.core.dtypes.dtypes import ExtensionDtype
from pandas.core.dtypes.generic import ABCDataFrame, ABCIndexClass, ABCSeries
from pandas.core.dtypes.generic import ABCDataFrame, ABCIndex, ABCSeries
from pandas.core.dtypes.missing import isna

from pandas.core import ops
Expand Down Expand Up @@ -1361,7 +1361,7 @@ def convert_values(param):
ovalues = [param] * len(self)
return ovalues

if isinstance(other, (ABCSeries, ABCIndexClass, ABCDataFrame)):
if isinstance(other, (ABCSeries, ABCIndex, ABCDataFrame)):
# rely on pandas to unbox and dispatch to us
return NotImplemented

Expand Down
6 changes: 3 additions & 3 deletions pandas/core/arrays/categorical.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@
needs_i8_conversion,
)
from pandas.core.dtypes.dtypes import CategoricalDtype
from pandas.core.dtypes.generic import ABCIndexClass, ABCSeries
from pandas.core.dtypes.generic import ABCIndex, ABCSeries
from pandas.core.dtypes.missing import is_valid_nat_for_dtype, isna, notna

from pandas.core import ops
Expand Down Expand Up @@ -321,7 +321,7 @@ def __init__(
if is_categorical_dtype(values):
if dtype.categories is None:
dtype = CategoricalDtype(values.categories, dtype.ordered)
elif not isinstance(values, (ABCIndexClass, ABCSeries)):
elif not isinstance(values, (ABCIndex, ABCSeries)):
# sanitize_array coerces np.nan to a string under certain versions
# of numpy
values = maybe_infer_to_datetimelike(values, convert_dates=True)
Expand Down Expand Up @@ -2514,7 +2514,7 @@ def _get_codes_for_values(values, categories) -> np.ndarray:
values = ensure_object(values)
categories = ensure_object(categories)

if isinstance(categories, ABCIndexClass):
if isinstance(categories, ABCIndex):
return coerce_indexer_dtype(categories.get_indexer_for(values), categories)

# Only hit here when we've already coerced to object dtypee.
Expand Down
6 changes: 3 additions & 3 deletions pandas/core/arrays/datetimes.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@
pandas_dtype,
)
from pandas.core.dtypes.dtypes import DatetimeTZDtype
from pandas.core.dtypes.generic import ABCIndexClass, ABCPandasArray, ABCSeries
from pandas.core.dtypes.generic import ABCIndex, ABCPandasArray, ABCSeries
from pandas.core.dtypes.missing import isna

from pandas.core.algorithms import checked_add_with_arr
Expand Down Expand Up @@ -216,7 +216,7 @@ class DatetimeArray(dtl.TimelikeOps, dtl.DatelikeOps):
_freq = None

def __init__(self, values, dtype=DT64NS_DTYPE, freq=None, copy=False):
if isinstance(values, (ABCSeries, ABCIndexClass)):
if isinstance(values, (ABCSeries, ABCIndex)):
values = values._values

inferred_freq = getattr(values, "_freq", None)
Expand Down Expand Up @@ -1947,7 +1947,7 @@ def sequence_to_dt64ns(
# if dtype has an embedded tz, capture it
tz = validate_tz_from_dtype(dtype, tz)

if isinstance(data, ABCIndexClass):
if isinstance(data, ABCIndex):
if data.nlevels > 1:
# Without this check, data._data below is None
raise TypeError("Cannot create a DatetimeArray from a MultiIndex.")
Expand Down
6 changes: 3 additions & 3 deletions pandas/core/arrays/period.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@
)
from pandas.core.dtypes.dtypes import PeriodDtype
from pandas.core.dtypes.generic import (
ABCIndexClass,
ABCIndex,
ABCPeriodIndex,
ABCSeries,
ABCTimedeltaArray,
Expand Down Expand Up @@ -964,14 +964,14 @@ def dt64arr_to_periodarr(data, freq, tz=None):
raise ValueError(f"Wrong dtype: {data.dtype}")

if freq is None:
if isinstance(data, ABCIndexClass):
if isinstance(data, ABCIndex):
data, freq = data._values, data.freq
elif isinstance(data, ABCSeries):
data, freq = data._values, data.dt.freq

freq = Period._maybe_convert_freq(freq)

if isinstance(data, (ABCIndexClass, ABCSeries)):
if isinstance(data, (ABCIndex, ABCSeries)):
data = data._values

base = freq._period_dtype_code
Expand Down
4 changes: 2 additions & 2 deletions pandas/core/arrays/sparse/array.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@
is_string_dtype,
pandas_dtype,
)
from pandas.core.dtypes.generic import ABCIndexClass, ABCSeries
from pandas.core.dtypes.generic import ABCIndex, ABCSeries
from pandas.core.dtypes.missing import isna, na_value_for_dtype, notna

import pandas.core.algorithms as algos
Expand Down Expand Up @@ -746,7 +746,7 @@ def value_counts(self, dropna=True):
keys = np.insert(keys, 0, self.fill_value)
counts = np.insert(counts, 0, fcounts)

if not isinstance(keys, ABCIndexClass):
if not isinstance(keys, ABCIndex):
keys = Index(keys)
return Series(counts, index=keys)

Expand Down
6 changes: 3 additions & 3 deletions pandas/core/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@
is_object_dtype,
is_scalar,
)
from pandas.core.dtypes.generic import ABCDataFrame, ABCIndexClass, ABCSeries
from pandas.core.dtypes.generic import ABCDataFrame, ABCIndex, ABCSeries
from pandas.core.dtypes.missing import isna, remove_na_arraylike

from pandas.core import algorithms
Expand Down Expand Up @@ -199,7 +199,7 @@ def _selection_name(self):
@property
def _selection_list(self):
if not isinstance(
self._selection, (list, tuple, ABCSeries, ABCIndexClass, np.ndarray)
self._selection, (list, tuple, ABCSeries, ABCIndex, np.ndarray)
):
return [self._selection]
return self._selection
Expand Down Expand Up @@ -254,7 +254,7 @@ def __getitem__(self, key):
if self._selection is not None:
raise IndexError(f"Column(s) {self._selection} already selected")

if isinstance(key, (list, tuple, ABCSeries, ABCIndexClass, np.ndarray)):
if isinstance(key, (list, tuple, ABCSeries, ABCIndex, np.ndarray)):
# pandas\core\base.py:217: error: "SelectionMixin" has no attribute
# "obj" [attr-defined]
if len(
Expand Down
10 changes: 4 additions & 6 deletions pandas/core/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
is_extension_array_dtype,
is_integer,
)
from pandas.core.dtypes.generic import ABCExtensionArray, ABCIndexClass, ABCSeries
from pandas.core.dtypes.generic import ABCExtensionArray, ABCIndex, ABCSeries
from pandas.core.dtypes.inference import iterable_not_string
from pandas.core.dtypes.missing import isna, isnull, notnull # noqa

Expand Down Expand Up @@ -100,7 +100,7 @@ def is_bool_indexer(key: Any) -> bool:
check_array_indexer : Check that `key` is a valid array to index,
and convert to an ndarray.
"""
if isinstance(key, (ABCSeries, np.ndarray, ABCIndexClass)) or (
if isinstance(key, (ABCSeries, np.ndarray, ABCIndex)) or (
is_array_like(key) and is_extension_array_dtype(key.dtype)
):
if key.dtype == np.object_:
Expand Down Expand Up @@ -199,7 +199,7 @@ def asarray_tuplesafe(values, dtype=None):

if not (isinstance(values, (list, tuple)) or hasattr(values, "__array__")):
values = list(values)
elif isinstance(values, ABCIndexClass):
elif isinstance(values, ABCIndex):
return values._values

if isinstance(values, list) and dtype in [np.object_, object]:
Expand Down Expand Up @@ -466,9 +466,7 @@ def convert_to_list_like(
Convert list-like or scalar input to list-like. List, numpy and pandas array-like
inputs are returned unmodified whereas others are converted to list.
"""
if isinstance(
values, (list, np.ndarray, ABCIndexClass, ABCSeries, ABCExtensionArray)
):
if isinstance(values, (list, np.ndarray, ABCIndex, ABCSeries, ABCExtensionArray)):
# np.ndarray resolving as Any gives a false positive
return values # type: ignore[return-value]
elif isinstance(values, abc.Iterable) and not isinstance(values, str):
Expand Down
8 changes: 3 additions & 5 deletions pandas/core/construction.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@
)
from pandas.core.dtypes.generic import (
ABCExtensionArray,
ABCIndexClass,
ABCIndex,
ABCPandasArray,
ABCSeries,
)
Expand Down Expand Up @@ -281,9 +281,7 @@ def array(
msg = f"Cannot pass scalar '{data}' to 'pandas.array'."
raise ValueError(msg)

if dtype is None and isinstance(
data, (ABCSeries, ABCIndexClass, ABCExtensionArray)
):
if dtype is None and isinstance(data, (ABCSeries, ABCIndex, ABCExtensionArray)):
dtype = data.dtype

data = extract_array(data, extract_numpy=True)
Expand Down Expand Up @@ -392,7 +390,7 @@ def extract_array(obj: object, extract_numpy: bool = False) -> Union[Any, ArrayL
>>> extract_array(pd.Series([1, 2, 3]), extract_numpy=True)
array([1, 2, 3])
"""
if isinstance(obj, (ABCIndexClass, ABCSeries)):
if isinstance(obj, (ABCIndex, ABCSeries)):
obj = obj.array

if extract_numpy and isinstance(obj, ABCPandasArray):
Expand Down
4 changes: 2 additions & 2 deletions pandas/core/dtypes/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
from pandas._typing import DtypeObj
from pandas.errors import AbstractMethodError

from pandas.core.dtypes.generic import ABCDataFrame, ABCIndexClass, ABCSeries
from pandas.core.dtypes.generic import ABCDataFrame, ABCIndex, ABCSeries

if TYPE_CHECKING:
from pandas.core.arrays import ExtensionArray
Expand Down Expand Up @@ -277,7 +277,7 @@ def is_dtype(cls, dtype: object) -> bool:
"""
dtype = getattr(dtype, "dtype", dtype)

if isinstance(dtype, (ABCSeries, ABCIndexClass, ABCDataFrame, np.dtype)):
if isinstance(dtype, (ABCSeries, ABCIndex, ABCDataFrame, np.dtype)):
# https://github.com/pandas-dev/pandas/issues/22960
# avoid passing data to `construct_from_string`. This could
# cause a FutureWarning from numpy about failing elementwise
Expand Down
4 changes: 2 additions & 2 deletions pandas/core/dtypes/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
IntervalDtype,
PeriodDtype,
)
from pandas.core.dtypes.generic import ABCCategorical, ABCIndexClass
from pandas.core.dtypes.generic import ABCCategorical, ABCIndex
from pandas.core.dtypes.inference import ( # noqa:F401
is_array_like,
is_bool,
Expand Down Expand Up @@ -1389,7 +1389,7 @@ def is_bool_dtype(arr_or_dtype) -> bool:
arr_or_dtype = arr_or_dtype.categories
# now we use the special definition for Index

if isinstance(arr_or_dtype, ABCIndexClass):
if isinstance(arr_or_dtype, ABCIndex):

# TODO(jreback)
# we don't have a boolean Index class
Expand Down
4 changes: 2 additions & 2 deletions pandas/core/dtypes/dtypes.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@
from pandas._typing import DtypeObj, Ordered

from pandas.core.dtypes.base import ExtensionDtype, register_extension_dtype
from pandas.core.dtypes.generic import ABCCategoricalIndex, ABCIndexClass
from pandas.core.dtypes.generic import ABCCategoricalIndex, ABCIndex
from pandas.core.dtypes.inference import is_bool, is_list_like

if TYPE_CHECKING:
Expand Down Expand Up @@ -499,7 +499,7 @@ def validate_categories(categories, fastpath: bool = False):
raise TypeError(
f"Parameter 'categories' must be list-like, was {repr(categories)}"
)
elif not isinstance(categories, ABCIndexClass):
elif not isinstance(categories, ABCIndex):
categories = Index(categories, tupleize_cols=False)

if not fastpath:
Expand Down
37 changes: 21 additions & 16 deletions pandas/core/dtypes/generic.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
DataFrame,
DatetimeIndex,
Float64Index,
Index,
Int64Index,
IntervalIndex,
MultiIndex,
Expand Down Expand Up @@ -76,24 +77,28 @@ def _check(cls, inst) -> bool:
"Type[IntervalIndex]",
create_pandas_abc_type("ABCIntervalIndex", "_typ", ("intervalindex",)),
)
ABCIndexClass = create_pandas_abc_type(
"ABCIndexClass",
"_typ",
{
"index",
"int64index",
"rangeindex",
"float64index",
"uint64index",
"multiindex",
"datetimeindex",
"timedeltaindex",
"periodindex",
"categoricalindex",
"intervalindex",
},
ABCIndex = cast(
"Type[Index]",
create_pandas_abc_type(
"ABCIndex",
"_typ",
{
"index",
"int64index",
"rangeindex",
"float64index",
"uint64index",
"multiindex",
"datetimeindex",
"timedeltaindex",
"periodindex",
"categoricalindex",
"intervalindex",
},
),
)


ABCNDFrame = cast(
"Type[NDFrame]",
create_pandas_abc_type("ABCNDFrame", "_typ", ("series", "dataframe")),
Expand Down
4 changes: 2 additions & 2 deletions pandas/core/dtypes/missing.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@
from pandas.core.dtypes.generic import (
ABCDataFrame,
ABCExtensionArray,
ABCIndexClass,
ABCIndex,
ABCMultiIndex,
ABCSeries,
)
Expand Down Expand Up @@ -156,7 +156,7 @@ def _isna(obj, inf_as_na: bool = False):
raise NotImplementedError("isna is not defined for MultiIndex")
elif isinstance(obj, type):
return False
elif isinstance(obj, (ABCSeries, np.ndarray, ABCIndexClass, ABCExtensionArray)):
elif isinstance(obj, (ABCSeries, np.ndarray, ABCIndex, ABCExtensionArray)):
return _isna_ndarraylike(obj, inf_as_na=inf_as_na)
elif isinstance(obj, ABCDataFrame):
return obj.isna()
Expand Down
Loading

0 comments on commit 466b855

Please sign in to comment.