From 67e95b83d3b1bdbbf802a41d23e5eb3ff7972fa3 Mon Sep 17 00:00:00 2001 From: Simon Hawkins Date: Sun, 10 Jan 2021 15:43:16 +0000 Subject: [PATCH] TYP: replace Label alias from pandas._typing with Hashable --- pandas/_typing.py | 15 ++++----- pandas/core/aggregation.py | 10 +++--- pandas/core/computation/parsing.py | 6 ++-- pandas/core/frame.py | 33 +++++++++---------- pandas/core/generic.py | 11 +++---- pandas/core/groupby/generic.py | 5 +-- pandas/core/groupby/groupby.py | 5 ++- pandas/core/groupby/grouper.py | 6 ++-- pandas/core/groupby/ops.py | 8 ++--- pandas/core/indexes/base.py | 26 ++++++++------- pandas/core/indexes/category.py | 10 +++--- pandas/core/indexes/datetimelike.py | 17 ++++++++-- pandas/core/indexes/extension.py | 5 ++- pandas/core/indexes/interval.py | 6 ++-- pandas/core/indexes/multi.py | 6 ++-- pandas/core/indexes/numeric.py | 6 ++-- pandas/core/indexes/range.py | 8 ++--- pandas/core/internals/construction.py | 18 +++++++--- pandas/core/internals/managers.py | 5 +-- pandas/core/reshape/concat.py | 13 ++++---- pandas/core/reshape/pivot.py | 11 ++++--- pandas/core/series.py | 16 ++++----- pandas/core/tools/datetimes.py | 7 ++-- pandas/io/formats/csvs.py | 27 ++++++++++----- pandas/io/formats/excel.py | 20 +++++++++--- pandas/io/formats/format.py | 4 +-- pandas/io/formats/style.py | 11 ++++--- pandas/io/pytables.py | 22 +++++-------- pandas/io/sas/sasreader.py | 10 +++--- pandas/io/stata.py | 47 +++++++++++++++------------ pandas/plotting/_core.py | 4 +-- pandas/plotting/_matplotlib/core.py | 9 +++-- pandas/plotting/_matplotlib/misc.py | 6 ++-- 33 files changed, 226 insertions(+), 187 deletions(-) diff --git a/pandas/_typing.py b/pandas/_typing.py index 0b50dd69f7abb..91cb01dac76fb 100644 --- a/pandas/_typing.py +++ b/pandas/_typing.py @@ -84,9 +84,8 @@ FrameOrSeries = TypeVar("FrameOrSeries", bound="NDFrame") Axis = Union[str, int] -Label = Optional[Hashable] -IndexLabel = Union[Label, Sequence[Label]] -Level = Union[Label, int] +IndexLabel = Union[Hashable, Sequence[Hashable]] +Level = Union[Hashable, int] Shape = Tuple[int, ...] Suffixes = Tuple[str, str] Ordered = Optional[bool] @@ -99,11 +98,11 @@ "ExtensionDtype", NpDtype, Type[Union[str, float, int, complex, bool, object]] ] # DtypeArg specifies all allowable dtypes in a functions its dtype argument -DtypeArg = Union[Dtype, Dict[Label, Dtype]] +DtypeArg = Union[Dtype, Dict[Hashable, Dtype]] DtypeObj = Union[np.dtype, "ExtensionDtype"] # For functions like rename that convert one label to another -Renamer = Union[Mapping[Label, Any], Callable[[Label], Label]] +Renamer = Union[Mapping[Hashable, Any], Callable[[Hashable], Hashable]] # to maintain type information across generic functions and parametrization T = TypeVar("T") @@ -120,7 +119,7 @@ # types of `func` kwarg for DataFrame.aggregate and Series.aggregate AggFuncTypeBase = Union[Callable, str] -AggFuncTypeDict = Dict[Label, Union[AggFuncTypeBase, List[AggFuncTypeBase]]] +AggFuncTypeDict = Dict[Hashable, Union[AggFuncTypeBase, List[AggFuncTypeBase]]] AggFuncType = Union[ AggFuncTypeBase, List[AggFuncTypeBase], @@ -155,8 +154,8 @@ FormattersType = Union[ List[Callable], Tuple[Callable, ...], Mapping[Union[str, int], Callable] ] -ColspaceType = Mapping[Label, Union[str, int]] +ColspaceType = Mapping[Hashable, Union[str, int]] FloatFormatType = Union[str, Callable, "EngFormatter"] ColspaceArgType = Union[ - str, int, Sequence[Union[str, int]], Mapping[Label, Union[str, int]] + str, int, Sequence[Union[str, int]], Mapping[Hashable, Union[str, int]] ] diff --git a/pandas/core/aggregation.py b/pandas/core/aggregation.py index cd169a250b49b..72a98da44428b 100644 --- a/pandas/core/aggregation.py +++ b/pandas/core/aggregation.py @@ -11,6 +11,7 @@ Callable, DefaultDict, Dict, + Hashable, Iterable, List, Optional, @@ -28,7 +29,6 @@ Axis, FrameOrSeries, FrameOrSeriesUnion, - Label, ) from pandas.core.dtypes.cast import is_nested_object @@ -294,9 +294,9 @@ def maybe_mangle_lambdas(agg_spec: Any) -> Any: def relabel_result( result: FrameOrSeries, func: Dict[str, List[Union[Callable, str]]], - columns: Iterable[Label], + columns: Iterable[Hashable], order: Iterable[int], -) -> Dict[Label, "Series"]: +) -> Dict[Hashable, "Series"]: """ Internal function to reorder result if relabelling is True for dataframe.agg, and return the reordered result in dict. @@ -323,7 +323,7 @@ def relabel_result( reordered_indexes = [ pair[0] for pair in sorted(zip(columns, order), key=lambda t: t[1]) ] - reordered_result_in_dict: Dict[Label, "Series"] = {} + reordered_result_in_dict: Dict[Hashable, "Series"] = {} idx = 0 reorder_mask = not isinstance(result, ABCSeries) and len(result.columns) > 1 @@ -493,7 +493,7 @@ def transform_dict_like( # GH 15931 - deprecation of renaming keys raise SpecificationError("nested renamer is not supported") - results: Dict[Label, FrameOrSeriesUnion] = {} + results: Dict[Hashable, FrameOrSeriesUnion] = {} for name, how in func.items(): colg = obj._gotitem(name, ndim=1) try: diff --git a/pandas/core/computation/parsing.py b/pandas/core/computation/parsing.py index 732b0650e5bd7..3c2f7f2793358 100644 --- a/pandas/core/computation/parsing.py +++ b/pandas/core/computation/parsing.py @@ -6,9 +6,7 @@ from keyword import iskeyword import token import tokenize -from typing import Iterator, Tuple - -from pandas._typing import Label +from typing import Hashable, Iterator, Tuple # A token value Python's tokenizer probably will never use. BACKTICK_QUOTED_STRING = 100 @@ -90,7 +88,7 @@ def clean_backtick_quoted_toks(tok: Tuple[int, str]) -> Tuple[int, str]: return toknum, tokval -def clean_column_name(name: "Label") -> "Label": +def clean_column_name(name: Hashable) -> Hashable: """ Function to emulate the cleaning of a backtick quoted name. diff --git a/pandas/core/frame.py b/pandas/core/frame.py index e65e9302dd4d5..3e331a7a23e17 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -61,7 +61,6 @@ FrameOrSeriesUnion, IndexKeyFunc, IndexLabel, - Label, Level, PythonFuncType, Renamer, @@ -992,7 +991,7 @@ def style(self) -> Styler: """ @Appender(_shared_docs["items"]) - def items(self) -> Iterable[Tuple[Label, Series]]: + def items(self) -> Iterable[Tuple[Hashable, Series]]: if self.columns.is_unique and hasattr(self, "_item_cache"): for k in self.columns: yield k, self._get_item_cache(k) @@ -1001,10 +1000,10 @@ def items(self) -> Iterable[Tuple[Label, Series]]: yield k, self._ixs(i, axis=1) @Appender(_shared_docs["items"]) - def iteritems(self) -> Iterable[Tuple[Label, Series]]: + def iteritems(self) -> Iterable[Tuple[Hashable, Series]]: yield from self.items() - def iterrows(self) -> Iterable[Tuple[Label, Series]]: + def iterrows(self) -> Iterable[Tuple[Hashable, Series]]: """ Iterate over DataFrame rows as (index, Series) pairs. @@ -2121,14 +2120,14 @@ def _from_arrays( def to_stata( self, path: FilePathOrBuffer, - convert_dates: Optional[Dict[Label, str]] = None, + convert_dates: Optional[Dict[Hashable, str]] = None, write_index: bool = True, byteorder: Optional[str] = None, time_stamp: Optional[datetime.datetime] = None, data_label: Optional[str] = None, - variable_labels: Optional[Dict[Label, str]] = None, + variable_labels: Optional[Dict[Hashable, str]] = None, version: Optional[int] = 114, - convert_strl: Optional[Sequence[Label]] = None, + convert_strl: Optional[Sequence[Hashable]] = None, compression: CompressionOptions = "infer", storage_options: StorageOptions = None, ) -> None: @@ -4483,7 +4482,7 @@ def fillna( downcast=downcast, ) - def pop(self, item: Label) -> Series: + def pop(self, item: Hashable) -> Series: """ Return item and drop from frame. Raise KeyError if not found. @@ -4546,7 +4545,7 @@ def replace( ) def _replace_columnwise( - self, mapping: Dict[Label, Tuple[Any, Any]], inplace: bool, regex + self, mapping: Dict[Hashable, Tuple[Any, Any]], inplace: bool, regex ): """ Dispatch to Series.replace column-wise. @@ -4724,7 +4723,7 @@ def set_index( "one-dimensional arrays." ) - missing: List[Label] = [] + missing: List[Hashable] = [] for col in keys: if isinstance(col, (Index, Series, np.ndarray, list, abc.Iterator)): # arrays are fine as long as they are one-dimensional @@ -4752,7 +4751,7 @@ def set_index( frame = self.copy() arrays = [] - names: List[Label] = [] + names: List[Hashable] = [] if append: names = list(self.index.names) if isinstance(self.index, MultiIndex): @@ -4761,7 +4760,7 @@ def set_index( else: arrays.append(self.index) - to_remove: List[Label] = [] + to_remove: List[Hashable] = [] for col in keys: if isinstance(col, MultiIndex): for n in range(col.nlevels): @@ -4819,7 +4818,7 @@ def reset_index( # type: ignore[misc] drop: bool = ..., inplace: Literal[False] = ..., col_level: Hashable = ..., - col_fill: Label = ..., + col_fill: Hashable = ..., ) -> DataFrame: ... @@ -4830,7 +4829,7 @@ def reset_index( drop: bool = ..., inplace: Literal[True] = ..., col_level: Hashable = ..., - col_fill: Label = ..., + col_fill: Hashable = ..., ) -> None: ... @@ -4840,7 +4839,7 @@ def reset_index( drop: bool = False, inplace: bool = False, col_level: Hashable = 0, - col_fill: Label = "", + col_fill: Hashable = "", ) -> Optional[DataFrame]: """ Reset the index, or a level of it. @@ -5630,7 +5629,7 @@ def sort_index( def value_counts( self, - subset: Optional[Sequence[Label]] = None, + subset: Optional[Sequence[Hashable]] = None, normalize: bool = False, sort: bool = True, ascending: bool = False, @@ -7511,7 +7510,7 @@ def diff(self, periods: int = 1, axis: Axis = 0) -> DataFrame: def _gotitem( self, - key: Union[Label, List[Label]], + key: IndexLabel, ndim: int, subset: Optional[FrameOrSeriesUnion] = None, ) -> FrameOrSeriesUnion: diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 2f4340c17c5a7..ce1e962614c58 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -44,7 +44,6 @@ IndexKeyFunc, IndexLabel, JSONSerializable, - Label, Level, NpDtype, Renamer, @@ -526,7 +525,7 @@ def _get_axis_resolvers(self, axis: str) -> Dict[str, Union[Series, MultiIndex]] return d @final - def _get_index_resolvers(self) -> Dict[Label, Union[Series, MultiIndex]]: + def _get_index_resolvers(self) -> Dict[Hashable, Union[Series, MultiIndex]]: from pandas.core.computation.parsing import clean_column_name d: Dict[str, Union[Series, MultiIndex]] = {} @@ -536,7 +535,7 @@ def _get_index_resolvers(self) -> Dict[Label, Union[Series, MultiIndex]]: return {clean_column_name(k): v for k, v in d.items() if not isinstance(k, int)} @final - def _get_cleaned_column_resolvers(self) -> Dict[Label, Series]: + def _get_cleaned_column_resolvers(self) -> Dict[Hashable, Series]: """ Return the special character free column resolvers of a dataframe. @@ -776,7 +775,7 @@ def droplevel(self: FrameOrSeries, level, axis=0) -> FrameOrSeries: result = self.set_axis(new_labels, axis=axis, inplace=False) return result - def pop(self, item: Label) -> Union[Series, Any]: + def pop(self, item: Hashable) -> Union[Series, Any]: result = self[item] del self[item] if self.ndim == 2: @@ -3225,7 +3224,7 @@ def to_csv( sep: str = ",", na_rep: str = "", float_format: Optional[str] = None, - columns: Optional[Sequence[Label]] = None, + columns: Optional[Sequence[Hashable]] = None, header: Union[bool_t, List[str]] = True, index: bool_t = True, index_label: Optional[IndexLabel] = None, @@ -10214,7 +10213,7 @@ def describe_1d(data) -> "Series": ldesc = [describe_1d(s) for _, s in data.items()] # set a convenient order for rows - names: List[Label] = [] + names: List[Hashable] = [] ldesc_indexes = sorted((x.index for x in ldesc), key=len) for idxnames in ldesc_indexes: for name in idxnames: diff --git a/pandas/core/groupby/generic.py b/pandas/core/groupby/generic.py index f2899a7ca704b..174a2f4052b06 100644 --- a/pandas/core/groupby/generic.py +++ b/pandas/core/groupby/generic.py @@ -15,6 +15,7 @@ Callable, Dict, FrozenSet, + Hashable, Iterable, List, Mapping, @@ -30,7 +31,7 @@ import numpy as np from pandas._libs import lib, reduction as libreduction -from pandas._typing import ArrayLike, FrameOrSeries, FrameOrSeriesUnion, Label +from pandas._typing import ArrayLike, FrameOrSeries, FrameOrSeriesUnion from pandas.util._decorators import Appender, Substitution, doc from pandas.core.dtypes.cast import ( @@ -1129,7 +1130,7 @@ def _aggregate_frame(self, func, *args, **kwargs) -> DataFrame: axis = self.axis obj = self._obj_with_exclusions - result: Dict[Label, Union[NDFrame, np.ndarray]] = {} + result: Dict[Hashable, Union[NDFrame, np.ndarray]] = {} if axis != obj._info_axis_number: for name, data in self: fres = func(data, *args, **kwargs) diff --git a/pandas/core/groupby/groupby.py b/pandas/core/groupby/groupby.py index aef4c036abc65..fff2f5b631e86 100644 --- a/pandas/core/groupby/groupby.py +++ b/pandas/core/groupby/groupby.py @@ -43,7 +43,6 @@ class providing the base-class of operations. FrameOrSeries, FrameOrSeriesUnion, IndexLabel, - Label, Scalar, final, ) @@ -522,7 +521,7 @@ def __init__( axis: int = 0, level: Optional[IndexLabel] = None, grouper: Optional["ops.BaseGrouper"] = None, - exclusions: Optional[Set[Label]] = None, + exclusions: Optional[Set[Hashable]] = None, selection: Optional[IndexLabel] = None, as_index: bool = True, sort: bool = True, @@ -860,7 +859,7 @@ def get_group(self, name, obj=None): return obj._take_with_is_copy(inds, axis=self.axis) - def __iter__(self) -> Iterator[Tuple[Label, FrameOrSeries]]: + def __iter__(self) -> Iterator[Tuple[Hashable, FrameOrSeries]]: """ Groupby iterator. diff --git a/pandas/core/groupby/grouper.py b/pandas/core/groupby/grouper.py index 26fb23087ed55..00cc762c7c136 100644 --- a/pandas/core/groupby/grouper.py +++ b/pandas/core/groupby/grouper.py @@ -7,7 +7,7 @@ import numpy as np -from pandas._typing import FrameOrSeries, Label, final +from pandas._typing import FrameOrSeries, final from pandas.errors import InvalidIndexError from pandas.util._decorators import cache_readonly @@ -616,7 +616,7 @@ def get_grouper( mutated: bool = False, validate: bool = True, dropna: bool = True, -) -> Tuple["ops.BaseGrouper", Set[Label], FrameOrSeries]: +) -> Tuple["ops.BaseGrouper", Set[Hashable], FrameOrSeries]: """ Create and return a BaseGrouper, which is an internal mapping of how to create the grouper indexers. @@ -741,7 +741,7 @@ def get_grouper( levels = [level] * len(keys) groupings: List[Grouping] = [] - exclusions: Set[Label] = set() + exclusions: Set[Hashable] = set() # if the actual grouper should be obj[key] def is_in_axis(key) -> bool: diff --git a/pandas/core/groupby/ops.py b/pandas/core/groupby/ops.py index 62d11183691f0..45897666b6ccf 100644 --- a/pandas/core/groupby/ops.py +++ b/pandas/core/groupby/ops.py @@ -24,7 +24,7 @@ from pandas._libs import NaT, iNaT, lib import pandas._libs.groupby as libgroupby import pandas._libs.reduction as libreduction -from pandas._typing import ArrayLike, F, FrameOrSeries, Label, Shape, final +from pandas._typing import ArrayLike, F, FrameOrSeries, Shape, final from pandas.errors import AbstractMethodError from pandas.util._decorators import cache_readonly @@ -134,7 +134,7 @@ def nkeys(self) -> int: def get_iterator( self, data: FrameOrSeries, axis: int = 0 - ) -> Iterator[Tuple[Label, FrameOrSeries]]: + ) -> Iterator[Tuple[Hashable, FrameOrSeries]]: """ Groupby iterator @@ -260,7 +260,7 @@ def levels(self) -> List[Index]: return [ping.group_index for ping in self.groupings] @property - def names(self) -> List[Label]: + def names(self) -> List[Hashable]: return [ping.name for ping in self.groupings] @final @@ -903,7 +903,7 @@ def levels(self) -> List[Index]: return [self.binlabels] @property - def names(self) -> List[Label]: + def names(self) -> List[Hashable]: return [self.binlabels.name] @property diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index a2e9737f305ba..b906e5642bde0 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -28,7 +28,7 @@ from pandas._libs.lib import is_datetime_array, no_default from pandas._libs.tslibs import IncompatibleFrequency, OutOfBoundsDatetime, Timestamp from pandas._libs.tslibs.timezones import tz_compare -from pandas._typing import AnyArrayLike, ArrayLike, Dtype, DtypeObj, Label, Shape, final +from pandas._typing import AnyArrayLike, ArrayLike, Dtype, DtypeObj, Shape, final from pandas.compat.numpy import function as nv from pandas.errors import DuplicateLabelError, InvalidIndexError from pandas.util._decorators import Appender, cache_readonly, doc @@ -235,7 +235,7 @@ def _outer_indexer(self, left, right): _typ = "index" _data: Union[ExtensionArray, np.ndarray] _id: Optional[_Identity] = None - _name: Label = None + _name: Hashable = None # MultiIndex.levels previously allowed setting the index name. We # don't allow this anymore, and raise if it happens rather than # failing silently. @@ -486,7 +486,7 @@ def asi8(self): return None @classmethod - def _simple_new(cls, values, name: Label = None): + def _simple_new(cls, values, name: Hashable = None): """ We require that we have a dtype compat for the values. If we are passed a non-dtype compat, then coerce using the constructor. @@ -570,7 +570,7 @@ def _get_attributes_dict(self): """ return {k: getattr(self, k, None) for k in self._attributes} - def _shallow_copy(self, values=None, name: Label = no_default): + def _shallow_copy(self, values=None, name: Hashable = no_default): """ Create a new Index with the same class as the caller, don't copy the data, use the same object attributes with passed in attributes taking @@ -888,10 +888,10 @@ def repeat(self, repeats, axis=None): def copy( self: _IndexT, - name: Optional[Label] = None, + name: Optional[Hashable] = None, deep: bool = False, dtype: Optional[Dtype] = None, - names: Optional[Sequence[Label]] = None, + names: Optional[Sequence[Hashable]] = None, ) -> _IndexT: """ Make a copy of this object. @@ -1308,7 +1308,9 @@ def name(self, value): self._name = value @final - def _validate_names(self, name=None, names=None, deep: bool = False) -> List[Label]: + def _validate_names( + self, name=None, names=None, deep: bool = False + ) -> List[Hashable]: """ Handles the quirks of having a singular 'name' parameter for general Index and plural 'names' parameter for MultiIndex. @@ -4506,7 +4508,7 @@ def append(self, other): return self._concat(to_concat, name) - def _concat(self, to_concat: List["Index"], name: Label) -> "Index": + def _concat(self, to_concat: List["Index"], name: Hashable) -> "Index": """ Concatenate multiple Index objects. """ @@ -5374,8 +5376,8 @@ def _get_string_slice(self, key: str_t): def slice_indexer( self, - start: Optional[Label] = None, - end: Optional[Label] = None, + start: Optional[Hashable] = None, + end: Optional[Hashable] = None, step: Optional[int] = None, kind: Optional[str_t] = None, ) -> slice: @@ -6114,7 +6116,7 @@ def default_index(n: int) -> "RangeIndex": return RangeIndex(0, n, name=None) -def maybe_extract_name(name, obj, cls) -> Label: +def maybe_extract_name(name, obj, cls) -> Hashable: """ If no name is passed, then extract it from data, validating hashability. """ @@ -6296,7 +6298,7 @@ def _try_convert_to_int_array( raise ValueError -def get_unanimous_names(*indexes: Index) -> Tuple[Label, ...]: +def get_unanimous_names(*indexes: Index) -> Tuple[Hashable, ...]: """ Return common name if all indices agree, otherwise None (level-by-level). diff --git a/pandas/core/indexes/category.py b/pandas/core/indexes/category.py index 24920e9b5faa7..a8a872ff38fb8 100644 --- a/pandas/core/indexes/category.py +++ b/pandas/core/indexes/category.py @@ -1,4 +1,4 @@ -from typing import Any, List, Optional +from typing import Any, Hashable, List, Optional import warnings import numpy as np @@ -7,7 +7,7 @@ from pandas._libs import index as libindex from pandas._libs.lib import no_default -from pandas._typing import ArrayLike, Dtype, Label +from pandas._typing import ArrayLike, Dtype from pandas.util._decorators import Appender, doc from pandas.core.dtypes.common import ( @@ -201,7 +201,7 @@ def __new__( return cls._simple_new(data, name=name) @classmethod - def _simple_new(cls, values: Categorical, name: Label = None): + def _simple_new(cls, values: Categorical, name: Optional[Hashable] = None): assert isinstance(values, Categorical), type(values) result = object.__new__(cls) @@ -221,7 +221,7 @@ def _simple_new(cls, values: Categorical, name: Label = None): def _shallow_copy( # type:ignore[override] self, values: Optional[Categorical] = None, - name: Label = no_default, + name: Hashable = no_default, ): name = self.name if name is no_default else name @@ -605,7 +605,7 @@ def map(self, mapper): mapped = self._values.map(mapper) return Index(mapped, name=self.name) - def _concat(self, to_concat: List["Index"], name: Label) -> Index: + def _concat(self, to_concat: List["Index"], name: Hashable) -> Index: # if calling index is category, don't check dtype of others try: codes = np.concatenate([self._is_dtype_compat(c).codes for c in to_concat]) diff --git a/pandas/core/indexes/datetimelike.py b/pandas/core/indexes/datetimelike.py index 7d214829b1871..50a4f589c59c1 100644 --- a/pandas/core/indexes/datetimelike.py +++ b/pandas/core/indexes/datetimelike.py @@ -2,13 +2,24 @@ Base and utility classes for tseries type pandas objects. """ from datetime import datetime -from typing import TYPE_CHECKING, Any, List, Optional, Tuple, Type, TypeVar, Union, cast +from typing import ( + TYPE_CHECKING, + Any, + Hashable, + List, + Optional, + Tuple, + Type, + TypeVar, + Union, + cast, +) import numpy as np from pandas._libs import NaT, Timedelta, iNaT, join as libjoin, lib from pandas._libs.tslibs import BaseOffset, Resolution, Tick -from pandas._typing import Callable, Label +from pandas._typing import Callable from pandas.compat.numpy import function as nv from pandas.util._decorators import Appender, cache_readonly, doc @@ -108,7 +119,7 @@ class DatetimeIndexOpsMixin(NDArrayBackedExtensionIndex): def _simple_new( cls, values: Union[DatetimeArray, TimedeltaArray, PeriodArray], - name: Label = None, + name: Optional[Hashable] = None, ): assert isinstance(values, cls._data_cls), type(values) diff --git a/pandas/core/indexes/extension.py b/pandas/core/indexes/extension.py index f597175bf2ae2..2c4f40d5275e1 100644 --- a/pandas/core/indexes/extension.py +++ b/pandas/core/indexes/extension.py @@ -1,12 +1,11 @@ """ Shared methods for Index subclasses backed by ExtensionArray. """ -from typing import List, Optional, TypeVar +from typing import Hashable, List, Optional, TypeVar import numpy as np from pandas._libs import lib -from pandas._typing import Label from pandas.compat.numpy import function as nv from pandas.errors import AbstractMethodError from pandas.util._decorators import cache_readonly, doc @@ -215,7 +214,7 @@ class ExtensionIndex(Index): @doc(Index._shallow_copy) def _shallow_copy( - self, values: Optional[ExtensionArray] = None, name: Label = lib.no_default + self, values: Optional[ExtensionArray] = None, name: Hashable = lib.no_default ): name = self.name if name is lib.no_default else name diff --git a/pandas/core/indexes/interval.py b/pandas/core/indexes/interval.py index b6213e99513c1..27e9f65995f07 100644 --- a/pandas/core/indexes/interval.py +++ b/pandas/core/indexes/interval.py @@ -2,7 +2,7 @@ from functools import wraps from operator import le, lt import textwrap -from typing import TYPE_CHECKING, Any, List, Optional, Tuple, Union, cast +from typing import TYPE_CHECKING, Any, Hashable, List, Optional, Tuple, Union, cast import numpy as np @@ -11,7 +11,7 @@ from pandas._libs import lib from pandas._libs.interval import Interval, IntervalMixin, IntervalTree from pandas._libs.tslibs import BaseOffset, Timedelta, Timestamp, to_offset -from pandas._typing import Dtype, DtypeObj, Label +from pandas._typing import Dtype, DtypeObj from pandas.errors import InvalidIndexError from pandas.util._decorators import Appender, cache_readonly from pandas.util._exceptions import rewrite_exception @@ -212,7 +212,7 @@ def __new__( return cls._simple_new(array, name) @classmethod - def _simple_new(cls, array: IntervalArray, name: Label = None): + def _simple_new(cls, array: IntervalArray, name: Hashable = None): """ Construct from an IntervalArray diff --git a/pandas/core/indexes/multi.py b/pandas/core/indexes/multi.py index f058645c4abda..485d4f809eabd 100644 --- a/pandas/core/indexes/multi.py +++ b/pandas/core/indexes/multi.py @@ -20,7 +20,7 @@ from pandas._libs import algos as libalgos, index as libindex, lib from pandas._libs.hashtable import duplicated_int64 -from pandas._typing import AnyArrayLike, DtypeObj, Label, Scalar, Shape +from pandas._typing import AnyArrayLike, DtypeObj, Scalar, Shape from pandas.compat.numpy import function as nv from pandas.errors import InvalidIndexError, PerformanceWarning, UnsortedIndexError from pandas.util._decorators import Appender, cache_readonly, doc @@ -475,7 +475,7 @@ def from_tuples( cls, tuples, sortorder: Optional[int] = None, - names: Optional[Sequence[Label]] = None, + names: Optional[Sequence[Hashable]] = None, ): """ Convert list of tuples to MultiIndex. @@ -517,7 +517,7 @@ def from_tuples( elif is_iterator(tuples): tuples = list(tuples) - arrays: List[Sequence[Label]] + arrays: List[Sequence[Hashable]] if len(tuples) == 0: if names is None: raise TypeError("Cannot infer number of levels from empty list") diff --git a/pandas/core/indexes/numeric.py b/pandas/core/indexes/numeric.py index 59793d1a63813..e5da085249acf 100644 --- a/pandas/core/indexes/numeric.py +++ b/pandas/core/indexes/numeric.py @@ -1,10 +1,10 @@ -from typing import Any, Optional +from typing import Any, Hashable, Optional import warnings import numpy as np from pandas._libs import index as libindex, lib -from pandas._typing import Dtype, DtypeObj, Label +from pandas._typing import Dtype, DtypeObj from pandas.util._decorators import doc from pandas.core.dtypes.cast import astype_nansafe @@ -115,7 +115,7 @@ def _maybe_cast_slice_bound(self, label, side: str, kind): # ---------------------------------------------------------------- @doc(Index._shallow_copy) - def _shallow_copy(self, values=None, name: Label = lib.no_default): + def _shallow_copy(self, values=None, name: Hashable = lib.no_default): if values is not None and not self._can_hold_na and values.dtype.kind == "f": name = self.name if name is lib.no_default else name # Ensure we are not returning an Int64Index with float data: diff --git a/pandas/core/indexes/range.py b/pandas/core/indexes/range.py index 4256ad93695e9..66a70fbea238a 100644 --- a/pandas/core/indexes/range.py +++ b/pandas/core/indexes/range.py @@ -1,14 +1,14 @@ from datetime import timedelta import operator from sys import getsizeof -from typing import Any, List, Optional, Tuple +from typing import Any, Hashable, List, Optional, Tuple import warnings import numpy as np from pandas._libs import index as libindex from pandas._libs.lib import no_default -from pandas._typing import Dtype, Label +from pandas._typing import Dtype from pandas.compat.numpy import function as nv from pandas.util._decorators import cache_readonly, doc @@ -139,7 +139,7 @@ def from_range( return cls._simple_new(data, name=name) @classmethod - def _simple_new(cls, values: range, name: Label = None) -> "RangeIndex": + def _simple_new(cls, values: range, name: Hashable = None) -> "RangeIndex": result = object.__new__(cls) assert isinstance(values, range) @@ -400,7 +400,7 @@ def __iter__(self): yield from self._range @doc(Int64Index._shallow_copy) - def _shallow_copy(self, values=None, name: Label = no_default): + def _shallow_copy(self, values=None, name: Hashable = no_default): name = self.name if name is no_default else name if values is not None: diff --git a/pandas/core/internals/construction.py b/pandas/core/internals/construction.py index f1cd221bae15c..5161cf7038fe8 100644 --- a/pandas/core/internals/construction.py +++ b/pandas/core/internals/construction.py @@ -3,13 +3,23 @@ constructors before passing them to a BlockManager. """ from collections import abc -from typing import TYPE_CHECKING, Any, Dict, List, Optional, Sequence, Tuple, Union +from typing import ( + TYPE_CHECKING, + Any, + Dict, + Hashable, + List, + Optional, + Sequence, + Tuple, + Union, +) import numpy as np import numpy.ma as ma from pandas._libs import lib -from pandas._typing import Axis, DtypeObj, Label, Scalar +from pandas._typing import Axis, DtypeObj, Scalar from pandas.core.dtypes.cast import ( construct_1d_arraylike_from_scalar, @@ -391,7 +401,7 @@ def extract_index(data) -> Index: index = Index([]) elif len(data) > 0: raw_lengths = [] - indexes: List[Union[List[Label], Index]] = [] + indexes: List[Union[List[Hashable], Index]] = [] have_raw_arrays = False have_series = False @@ -459,7 +469,7 @@ def _get_names_from_index(data): if not has_some_name: return ibase.default_index(len(data)) - index: List[Label] = list(range(len(data))) + index: List[Hashable] = list(range(len(data))) count = 0 for i, s in enumerate(data): n = getattr(s, "name", None) diff --git a/pandas/core/internals/managers.py b/pandas/core/internals/managers.py index d27efd98ab079..fd503280eeafb 100644 --- a/pandas/core/internals/managers.py +++ b/pandas/core/internals/managers.py @@ -5,6 +5,7 @@ Callable, DefaultDict, Dict, + Hashable, List, Optional, Sequence, @@ -17,7 +18,7 @@ import numpy as np from pandas._libs import internals as libinternals, lib -from pandas._typing import ArrayLike, Dtype, DtypeObj, Label, Shape +from pandas._typing import ArrayLike, Dtype, DtypeObj, Shape from pandas.errors import PerformanceWarning from pandas.util._validators import validate_bool_kwarg @@ -1166,7 +1167,7 @@ def value_getitem(placement): # Newly created block's dtype may already be present. self._known_consolidated = False - def insert(self, loc: int, item: Label, value, allow_duplicates: bool = False): + def insert(self, loc: int, item: Hashable, value, allow_duplicates: bool = False): """ Insert item at selected position. diff --git a/pandas/core/reshape/concat.py b/pandas/core/reshape/concat.py index 5799b579fd0dc..d4729a0a59baa 100644 --- a/pandas/core/reshape/concat.py +++ b/pandas/core/reshape/concat.py @@ -5,6 +5,7 @@ from collections import abc from typing import ( TYPE_CHECKING, + Hashable, Iterable, List, Mapping, @@ -17,7 +18,7 @@ import numpy as np -from pandas._typing import FrameOrSeriesUnion, Label +from pandas._typing import FrameOrSeriesUnion from pandas.util._decorators import cache_readonly from pandas.core.dtypes.concat import concat_compat @@ -50,7 +51,7 @@ @overload def concat( - objs: Union[Iterable["DataFrame"], Mapping[Label, "DataFrame"]], + objs: Union[Iterable["DataFrame"], Mapping[Hashable, "DataFrame"]], axis=0, join: str = "outer", ignore_index: bool = False, @@ -66,7 +67,7 @@ def concat( @overload def concat( - objs: Union[Iterable["NDFrame"], Mapping[Label, "NDFrame"]], + objs: Union[Iterable["NDFrame"], Mapping[Hashable, "NDFrame"]], axis=0, join: str = "outer", ignore_index: bool = False, @@ -81,7 +82,7 @@ def concat( def concat( - objs: Union[Iterable["NDFrame"], Mapping[Label, "NDFrame"]], + objs: Union[Iterable["NDFrame"], Mapping[Hashable, "NDFrame"]], axis=0, join="outer", ignore_index: bool = False, @@ -306,7 +307,7 @@ class _Concatenator: def __init__( self, - objs: Union[Iterable["NDFrame"], Mapping[Label, "NDFrame"]], + objs: Union[Iterable["NDFrame"], Mapping[Hashable, "NDFrame"]], axis=0, join: str = "outer", keys=None, @@ -560,7 +561,7 @@ def _get_concat_axis(self) -> Index: idx = ibase.default_index(len(self.objs)) return idx elif self.keys is None: - names: List[Label] = [None] * len(self.objs) + names: List[Hashable] = [None] * len(self.objs) num = 0 has_names = False for i, x in enumerate(self.objs): diff --git a/pandas/core/reshape/pivot.py b/pandas/core/reshape/pivot.py index bdbd8c7b8dff6..4c335802e5546 100644 --- a/pandas/core/reshape/pivot.py +++ b/pandas/core/reshape/pivot.py @@ -4,6 +4,7 @@ TYPE_CHECKING, Callable, Dict, + Hashable, List, Optional, Sequence, @@ -15,7 +16,7 @@ import numpy as np -from pandas._typing import FrameOrSeriesUnion, Label +from pandas._typing import FrameOrSeriesUnion, IndexLabel from pandas.util._decorators import Appender, Substitution from pandas.core.dtypes.cast import maybe_downcast_to_dtype @@ -424,9 +425,9 @@ def _convert_by(by): @Appender(_shared_docs["pivot"], indents=1) def pivot( data: DataFrame, - index: Optional[Union[Label, Sequence[Label]]] = None, - columns: Optional[Union[Label, Sequence[Label]]] = None, - values: Optional[Union[Label, Sequence[Label]]] = None, + index: Optional[IndexLabel] = None, + columns: Optional[IndexLabel] = None, + values: Optional[IndexLabel] = None, ) -> "DataFrame": if columns is None: raise TypeError("pivot() missing 1 required argument: 'columns'") @@ -454,7 +455,7 @@ def pivot( if is_list_like(values) and not isinstance(values, tuple): # Exclude tuple because it is seen as a single column name - values = cast(Sequence[Label], values) + values = cast(Sequence[Hashable], values) indexed = data._constructor( data[values]._values, index=index, columns=values ) diff --git a/pandas/core/series.py b/pandas/core/series.py index 6586ac8b01840..f8b1acdfb52e6 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -9,6 +9,7 @@ TYPE_CHECKING, Any, Callable, + Hashable, Iterable, List, Optional, @@ -32,7 +33,6 @@ DtypeObj, FrameOrSeriesUnion, IndexKeyFunc, - Label, NpDtype, StorageOptions, ValueKeyFunc, @@ -193,7 +193,7 @@ class Series(base.IndexOpsMixin, generic.NDFrame): _typ = "series" _HANDLED_TYPES = (Index, ExtensionArray, np.ndarray) - _name: Label + _name: Hashable _metadata: List[str] = ["name"] _internal_names_set = {"index"} | generic.NDFrame._internal_names_set _accessors = {"dt", "cat", "str", "sparse"} @@ -462,7 +462,7 @@ def dtypes(self) -> DtypeObj: return self.dtype @property - def name(self) -> Label: + def name(self) -> Hashable: """ Return the name of the Series. @@ -512,7 +512,7 @@ def name(self) -> Label: return self._name @name.setter - def name(self, value: Label) -> None: + def name(self, value: Hashable) -> None: validate_all_hashable(value, error_name=f"{type(self).__name__}.name") object.__setattr__(self, "_name", value) @@ -1453,7 +1453,7 @@ def to_markdown( # ---------------------------------------------------------------------- - def items(self) -> Iterable[Tuple[Label, Any]]: + def items(self) -> Iterable[Tuple[Hashable, Any]]: """ Lazily iterate over (index, value) tuples. @@ -1483,7 +1483,7 @@ def items(self) -> Iterable[Tuple[Label, Any]]: return zip(iter(self.index), iter(self)) @Appender(items.__doc__) - def iteritems(self) -> Iterable[Tuple[Label, Any]]: + def iteritems(self) -> Iterable[Tuple[Hashable, Any]]: return self.items() # ---------------------------------------------------------------------- @@ -2706,7 +2706,7 @@ def _binop(self, other, func, level=None, fill_value=None): return ret def _construct_result( - self, result: Union[ArrayLike, Tuple[ArrayLike, ArrayLike]], name: Label + self, result: Union[ArrayLike, Tuple[ArrayLike, ArrayLike]], name: Hashable ) -> Union["Series", Tuple["Series", "Series"]]: """ Construct an appropriately-labelled Series from the result of an op. @@ -4403,7 +4403,7 @@ def fillna( downcast=downcast, ) - def pop(self, item: Label) -> Any: + def pop(self, item: Hashable) -> Any: """ Return item and drops from series. Raise KeyError if not found. diff --git a/pandas/core/tools/datetimes.py b/pandas/core/tools/datetimes.py index 56e171e1a5db1..aff55bc0a1fd5 100644 --- a/pandas/core/tools/datetimes.py +++ b/pandas/core/tools/datetimes.py @@ -5,6 +5,7 @@ from typing import ( TYPE_CHECKING, Callable, + Hashable, List, Optional, Tuple, @@ -32,7 +33,7 @@ guess_datetime_format, ) from pandas._libs.tslibs.strptime import array_strptime -from pandas._typing import AnyArrayLike, ArrayLike, Label, Timezone +from pandas._typing import AnyArrayLike, ArrayLike, Timezone from pandas.core.dtypes.common import ( ensure_object, @@ -181,7 +182,7 @@ def _maybe_cache( def _box_as_indexlike( - dt_array: ArrayLike, utc: Optional[bool] = None, name: Label = None + dt_array: ArrayLike, utc: Optional[bool] = None, name: Hashable = None ) -> Index: """ Properly boxes the ndarray of datetimes to DatetimeIndex @@ -267,7 +268,7 @@ def _return_parsed_timezone_results(result, timezones, tz, name): def _convert_listlike_datetimes( arg, format: Optional[str], - name: Label = None, + name: Hashable = None, tz: Optional[Timezone] = None, unit: Optional[str] = None, errors: Optional[str] = None, diff --git a/pandas/io/formats/csvs.py b/pandas/io/formats/csvs.py index 65c51c78383a9..74756b0c57092 100644 --- a/pandas/io/formats/csvs.py +++ b/pandas/io/formats/csvs.py @@ -4,7 +4,17 @@ import csv as csvlib import os -from typing import TYPE_CHECKING, Any, Dict, Iterator, List, Optional, Sequence, Union +from typing import ( + TYPE_CHECKING, + Any, + Dict, + Hashable, + Iterator, + List, + Optional, + Sequence, + Union, +) import numpy as np @@ -14,7 +24,6 @@ FilePathOrBuffer, FloatFormatType, IndexLabel, - Label, StorageOptions, ) @@ -40,7 +49,7 @@ def __init__( formatter: "DataFrameFormatter", path_or_buf: FilePathOrBuffer[str] = "", sep: str = ",", - cols: Optional[Sequence[Label]] = None, + cols: Optional[Sequence[Hashable]] = None, index_label: Optional[IndexLabel] = None, mode: str = "w", encoding: Optional[str] = None, @@ -129,7 +138,9 @@ def _initialize_quotechar(self, quotechar: Optional[str]) -> Optional[str]: def has_mi_columns(self) -> bool: return bool(isinstance(self.obj.columns, ABCMultiIndex)) - def _initialize_columns(self, cols: Optional[Sequence[Label]]) -> Sequence[Label]: + def _initialize_columns( + self, cols: Optional[Sequence[Hashable]] + ) -> Sequence[Hashable]: # validate mi options if self.has_mi_columns: if cols is not None: @@ -195,7 +206,7 @@ def _need_to_save_header(self) -> bool: return bool(self._has_aliases or self.header) @property - def write_cols(self) -> Sequence[Label]: + def write_cols(self) -> Sequence[Hashable]: if self._has_aliases: assert not isinstance(self.header, bool) if len(self.header) != len(self.cols): @@ -208,8 +219,8 @@ def write_cols(self) -> Sequence[Label]: return self.cols @property - def encoded_labels(self) -> List[Label]: - encoded_labels: List[Label] = [] + def encoded_labels(self) -> List[Hashable]: + encoded_labels: List[Hashable] = [] if self.index and self.index_label: assert isinstance(self.index_label, Sequence) @@ -259,7 +270,7 @@ def _save_header(self) -> None: for row in self._generate_multiindex_header_rows(): self.writer.writerow(row) - def _generate_multiindex_header_rows(self) -> Iterator[List[Label]]: + def _generate_multiindex_header_rows(self) -> Iterator[List[Hashable]]: columns = self.obj.columns for i in range(columns.nlevels): # we need at least 1 index column to write our col names diff --git a/pandas/io/formats/excel.py b/pandas/io/formats/excel.py index 0cad67169feff..b027d8139f24b 100644 --- a/pandas/io/formats/excel.py +++ b/pandas/io/formats/excel.py @@ -5,13 +5,23 @@ from functools import reduce import itertools import re -from typing import Callable, Dict, Iterable, Mapping, Optional, Sequence, Union, cast +from typing import ( + Callable, + Dict, + Hashable, + Iterable, + Mapping, + Optional, + Sequence, + Union, + cast, +) import warnings import numpy as np from pandas._libs.lib import is_list_like -from pandas._typing import Label, StorageOptions +from pandas._typing import IndexLabel, StorageOptions from pandas.util._decorators import doc from pandas.core.dtypes import missing @@ -440,10 +450,10 @@ def __init__( df, na_rep: str = "", float_format: Optional[str] = None, - cols: Optional[Sequence[Label]] = None, - header: Union[Sequence[Label], bool] = True, + cols: Optional[Sequence[Hashable]] = None, + header: Union[Sequence[Hashable], bool] = True, index: bool = True, - index_label: Optional[Union[Label, Sequence[Label]]] = None, + index_label: Optional[IndexLabel] = None, merge_cells: bool = False, inf_rep: str = "inf", style_converter: Optional[Callable] = None, diff --git a/pandas/io/formats/format.py b/pandas/io/formats/format.py index 6426f9e780eef..2c17551a7c3b9 100644 --- a/pandas/io/formats/format.py +++ b/pandas/io/formats/format.py @@ -18,6 +18,7 @@ Any, Callable, Dict, + Hashable, Iterable, List, Mapping, @@ -47,7 +48,6 @@ FloatFormatType, FormattersType, IndexLabel, - Label, StorageOptions, ) @@ -1032,7 +1032,7 @@ def to_csv( path_or_buf: Optional[FilePathOrBuffer[str]] = None, encoding: Optional[str] = None, sep: str = ",", - columns: Optional[Sequence[Label]] = None, + columns: Optional[Sequence[Hashable]] = None, index_label: Optional[IndexLabel] = None, mode: str = "w", compression: CompressionOptions = "infer", diff --git a/pandas/io/formats/style.py b/pandas/io/formats/style.py index 6ed31f38893dc..b6c1336ede597 100644 --- a/pandas/io/formats/style.py +++ b/pandas/io/formats/style.py @@ -11,6 +11,7 @@ Callable, DefaultDict, Dict, + Hashable, List, Optional, Sequence, @@ -24,7 +25,7 @@ from pandas._config import get_option from pandas._libs import lib -from pandas._typing import Axis, FrameOrSeries, FrameOrSeriesUnion, Label +from pandas._typing import Axis, FrameOrSeries, FrameOrSeriesUnion, IndexLabel from pandas.compat._optional import import_optional_dependency from pandas.util._decorators import doc @@ -215,10 +216,10 @@ def to_excel( sheet_name: str = "Sheet1", na_rep: str = "", float_format: Optional[str] = None, - columns: Optional[Sequence[Label]] = None, - header: Union[Sequence[Label], bool] = True, + columns: Optional[Sequence[Hashable]] = None, + header: Union[Sequence[Hashable], bool] = True, index: bool = True, - index_label: Optional[Union[Label, Sequence[Label]]] = None, + index_label: Optional[IndexLabel] = None, startrow: int = 0, startcol: int = 0, engine: Optional[str] = None, @@ -1139,7 +1140,7 @@ def _highlight_null(v, null_color: str) -> str: def highlight_null( self, null_color: str = "red", - subset: Optional[Union[Label, Sequence[Label]]] = None, + subset: Optional[IndexLabel] = None, ) -> "Styler": """ Shade the background ``null_color`` for missing values. diff --git a/pandas/io/pytables.py b/pandas/io/pytables.py index d2b02038f8b78..d1275590306ef 100644 --- a/pandas/io/pytables.py +++ b/pandas/io/pytables.py @@ -14,6 +14,7 @@ Any, Callable, Dict, + Hashable, List, Optional, Sequence, @@ -29,14 +30,7 @@ from pandas._libs import lib, writers as libwriters from pandas._libs.tslibs import timezones -from pandas._typing import ( - ArrayLike, - DtypeArg, - FrameOrSeries, - FrameOrSeriesUnion, - Label, - Shape, -) +from pandas._typing import ArrayLike, DtypeArg, FrameOrSeries, FrameOrSeriesUnion, Shape from pandas.compat._optional import import_optional_dependency from pandas.compat.pickle_compat import patch_pickle from pandas.errors import PerformanceWarning @@ -2935,7 +2929,7 @@ def read_multi_index( levels = [] codes = [] - names: List[Label] = [] + names: List[Hashable] = [] for i in range(nlevels): level_key = f"{key}_level{i}" node = getattr(self.group, level_key) @@ -3084,7 +3078,7 @@ class SeriesFixed(GenericFixed): pandas_kind = "series" attributes = ["name"] - name: Label + name: Hashable @property def shape(self): @@ -3235,7 +3229,7 @@ class Table(Fixed): pandas_kind = "wide_table" format_type: str = "table" # GH#30962 needed by dask table_type: str - levels: Union[int, List[Label]] = 1 + levels: Union[int, List[Hashable]] = 1 is_table = True index_axes: List[IndexCol] @@ -3333,7 +3327,7 @@ def is_multi_index(self) -> bool: def validate_multiindex( self, obj: FrameOrSeriesUnion - ) -> Tuple[DataFrame, List[Label]]: + ) -> Tuple[DataFrame, List[Hashable]]: """ validate that we can store the multi-index; reset and return the new object @@ -3476,7 +3470,7 @@ def get_attrs(self): self.nan_rep = getattr(self.attrs, "nan_rep", None) self.encoding = _ensure_encoding(getattr(self.attrs, "encoding", None)) self.errors = _ensure_decoded(getattr(self.attrs, "errors", "strict")) - self.levels: List[Label] = getattr(self.attrs, "levels", None) or [] + self.levels: List[Hashable] = getattr(self.attrs, "levels", None) or [] self.index_axes = [a for a in self.indexables if a.is_an_indexable] self.values_axes = [a for a in self.indexables if not a.is_an_indexable] @@ -4622,7 +4616,7 @@ class GenericTable(AppendableFrameTable): table_type = "generic_table" ndim = 2 obj_type = DataFrame - levels: List[Label] + levels: List[Hashable] @property def pandas_type(self) -> str: diff --git a/pandas/io/sas/sasreader.py b/pandas/io/sas/sasreader.py index 243218129fda6..d193971a6721e 100644 --- a/pandas/io/sas/sasreader.py +++ b/pandas/io/sas/sasreader.py @@ -2,9 +2,9 @@ Read SAS sas7bdat or xport files. """ from abc import ABCMeta, abstractmethod -from typing import TYPE_CHECKING, Optional, Union, overload +from typing import TYPE_CHECKING, Hashable, Optional, Union, overload -from pandas._typing import FilePathOrBuffer, Label +from pandas._typing import FilePathOrBuffer from pandas.io.common import stringify_path @@ -37,7 +37,7 @@ def __exit__(self, exc_type, exc_value, traceback): def read_sas( filepath_or_buffer: FilePathOrBuffer, format: Optional[str] = ..., - index: Optional[Label] = ..., + index: Optional[Hashable] = ..., encoding: Optional[str] = ..., chunksize: int = ..., iterator: bool = ..., @@ -49,7 +49,7 @@ def read_sas( def read_sas( filepath_or_buffer: FilePathOrBuffer, format: Optional[str] = ..., - index: Optional[Label] = ..., + index: Optional[Hashable] = ..., encoding: Optional[str] = ..., chunksize: None = ..., iterator: bool = ..., @@ -60,7 +60,7 @@ def read_sas( def read_sas( filepath_or_buffer: FilePathOrBuffer, format: Optional[str] = None, - index: Optional[Label] = None, + index: Optional[Hashable] = None, encoding: Optional[str] = None, chunksize: Optional[int] = None, iterator: bool = False, diff --git a/pandas/io/stata.py b/pandas/io/stata.py index 88485f99c07aa..f3a74189eba85 100644 --- a/pandas/io/stata.py +++ b/pandas/io/stata.py @@ -16,7 +16,18 @@ from pathlib import Path import struct import sys -from typing import Any, AnyStr, Dict, List, Optional, Sequence, Tuple, Union, cast +from typing import ( + Any, + AnyStr, + Dict, + Hashable, + List, + Optional, + Sequence, + Tuple, + Union, + cast, +) import warnings from dateutil.relativedelta import relativedelta @@ -24,13 +35,7 @@ from pandas._libs.lib import infer_dtype from pandas._libs.writers import max_len_string_array -from pandas._typing import ( - Buffer, - CompressionOptions, - FilePathOrBuffer, - Label, - StorageOptions, -) +from pandas._typing import Buffer, CompressionOptions, FilePathOrBuffer, StorageOptions from pandas.util._decorators import Appender, doc from pandas.core.dtypes.common import ( @@ -1959,7 +1964,7 @@ def _convert_datetime_to_stata_type(fmt: str) -> np.dtype: raise NotImplementedError(f"Format {fmt} not implemented") -def _maybe_convert_to_int_keys(convert_dates: Dict, varlist: List[Label]) -> Dict: +def _maybe_convert_to_int_keys(convert_dates: Dict, varlist: List[Hashable]) -> Dict: new_dict = {} for key in convert_dates: if not convert_dates[key].startswith("%"): # make sure proper fmts @@ -2144,12 +2149,12 @@ def __init__( self, fname: FilePathOrBuffer, data: DataFrame, - convert_dates: Optional[Dict[Label, str]] = None, + convert_dates: Optional[Dict[Hashable, str]] = None, write_index: bool = True, byteorder: Optional[str] = None, time_stamp: Optional[datetime.datetime] = None, data_label: Optional[str] = None, - variable_labels: Optional[Dict[Label, str]] = None, + variable_labels: Optional[Dict[Hashable, str]] = None, compression: CompressionOptions = "infer", storage_options: StorageOptions = None, ): @@ -2170,7 +2175,7 @@ def __init__( self._byteorder = _set_endianness(byteorder) self._fname = fname self.type_converters = {253: np.int32, 252: np.int16, 251: np.int8} - self._converted_names: Dict[Label, str] = {} + self._converted_names: Dict[Hashable, str] = {} def _write(self, to_write: str) -> None: """ @@ -2292,8 +2297,8 @@ def _check_column_names(self, data: DataFrame) -> DataFrame: dates are exported, the variable name is propagated to the date conversion dictionary """ - converted_names: Dict[Label, str] = {} - columns: List[Label] = list(data.columns) + converted_names: Dict[Hashable, str] = {} + columns = list(data.columns) original_columns = columns[:] duplicate_var_id = 0 @@ -3023,18 +3028,18 @@ def __init__( self, fname: FilePathOrBuffer, data: DataFrame, - convert_dates: Optional[Dict[Label, str]] = None, + convert_dates: Optional[Dict[Hashable, str]] = None, write_index: bool = True, byteorder: Optional[str] = None, time_stamp: Optional[datetime.datetime] = None, data_label: Optional[str] = None, - variable_labels: Optional[Dict[Label, str]] = None, - convert_strl: Optional[Sequence[Label]] = None, + variable_labels: Optional[Dict[Hashable, str]] = None, + convert_strl: Optional[Sequence[Hashable]] = None, compression: CompressionOptions = "infer", storage_options: StorageOptions = None, ): # Copy to new list since convert_strl might be modified later - self._convert_strl: List[Label] = [] + self._convert_strl: List[Hashable] = [] if convert_strl is not None: self._convert_strl.extend(convert_strl) @@ -3424,13 +3429,13 @@ def __init__( self, fname: FilePathOrBuffer, data: DataFrame, - convert_dates: Optional[Dict[Label, str]] = None, + convert_dates: Optional[Dict[Hashable, str]] = None, write_index: bool = True, byteorder: Optional[str] = None, time_stamp: Optional[datetime.datetime] = None, data_label: Optional[str] = None, - variable_labels: Optional[Dict[Label, str]] = None, - convert_strl: Optional[Sequence[Label]] = None, + variable_labels: Optional[Dict[Hashable, str]] = None, + convert_strl: Optional[Sequence[Hashable]] = None, version: Optional[int] = None, compression: CompressionOptions = "infer", storage_options: StorageOptions = None, diff --git a/pandas/plotting/_core.py b/pandas/plotting/_core.py index ab8f94596ff1a..597217ec67b0e 100644 --- a/pandas/plotting/_core.py +++ b/pandas/plotting/_core.py @@ -5,7 +5,7 @@ from pandas._config import get_option -from pandas._typing import Label +from pandas._typing import IndexLabel from pandas.util._decorators import Appender, Substitution from pandas.core.dtypes.common import is_integer, is_list_like @@ -102,7 +102,7 @@ def hist_series( def hist_frame( data: DataFrame, - column: Union[Label, Sequence[Label]] = None, + column: IndexLabel = None, by=None, grid: bool = True, xlabelsize: Optional[int] = None, diff --git a/pandas/plotting/_matplotlib/core.py b/pandas/plotting/_matplotlib/core.py index f0e15c19da5d3..aa8e0665a7310 100644 --- a/pandas/plotting/_matplotlib/core.py +++ b/pandas/plotting/_matplotlib/core.py @@ -1,10 +1,9 @@ -from typing import TYPE_CHECKING, List, Optional, Tuple +from typing import TYPE_CHECKING, Hashable, List, Optional, Tuple import warnings from matplotlib.artist import Artist import numpy as np -from pandas._typing import Label from pandas.errors import AbstractMethodError from pandas.util._decorators import cache_readonly @@ -107,8 +106,8 @@ def __init__( ylim=None, xticks=None, yticks=None, - xlabel: Optional[Label] = None, - ylabel: Optional[Label] = None, + xlabel: Optional[Hashable] = None, + ylabel: Optional[Hashable] = None, sort_columns=False, fontsize=None, secondary_y=False, @@ -170,7 +169,7 @@ def __init__( self.grid = grid self.legend = legend self.legend_handles: List[Artist] = [] - self.legend_labels: List[Label] = [] + self.legend_labels: List[Hashable] = [] self.logx = kwds.pop("logx", False) self.logy = kwds.pop("logy", False) diff --git a/pandas/plotting/_matplotlib/misc.py b/pandas/plotting/_matplotlib/misc.py index 64078abfd9220..d0c05af5dce8b 100644 --- a/pandas/plotting/_matplotlib/misc.py +++ b/pandas/plotting/_matplotlib/misc.py @@ -1,14 +1,12 @@ from __future__ import annotations import random -from typing import TYPE_CHECKING, Dict, List, Optional, Set +from typing import TYPE_CHECKING, Dict, Hashable, List, Optional, Set import matplotlib.lines as mlines import matplotlib.patches as patches import numpy as np -from pandas._typing import Label - from pandas.core.dtypes.missing import notna from pandas.io.formats.printing import pprint_thing @@ -150,7 +148,7 @@ def normalize(series): ax.set_xlim(-1, 1) ax.set_ylim(-1, 1) - to_plot: Dict[Label, List[List]] = {} + to_plot: Dict[Hashable, List[List]] = {} colors = get_standard_colors( num_colors=len(classes), colormap=colormap, color_type="random", color=color )