Skip to content

Commit 0a3b2f7

Browse files
committed
TYPIMG: Partial typing of Categorical
1 parent 3b96ada commit 0a3b2f7

File tree

3 files changed

+26
-16
lines changed

3 files changed

+26
-16
lines changed

pandas/_typing.py

+3
Original file line numberDiff line numberDiff line change
@@ -27,3 +27,6 @@
2727
FrameOrSeries = TypeVar("FrameOrSeries", "Series", "DataFrame")
2828
Scalar = Union[str, int, float]
2929
Axis = Union[str, int]
30+
31+
# TODO(GH26403): Replace with Optional[bool] or bool
32+
OrderedType = Union[None, bool, object]

pandas/core/arrays/categorical.py

+15-11
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
from shutil import get_terminal_size
22
import textwrap
3+
from typing import Type, Union, cast
34
from warnings import warn
45

56
import numpy as np
@@ -47,6 +48,7 @@
4748
from pandas.core.dtypes.inference import is_hashable
4849
from pandas.core.dtypes.missing import isna, notna
4950

51+
from pandas._typing import ArrayLike, Dtype, OrderedType
5052
from pandas.core import ops
5153
from pandas.core.accessor import PandasDelegate, delegate_names
5254
import pandas.core.algorithms as algorithms
@@ -473,7 +475,7 @@ def categories(self, categories):
473475
self._dtype = new_dtype
474476

475477
@property
476-
def ordered(self):
478+
def ordered(self) -> OrderedType:
477479
"""
478480
Whether the categories have an ordered relationship.
479481
"""
@@ -487,11 +489,11 @@ def dtype(self) -> CategoricalDtype:
487489
return self._dtype
488490

489491
@property
490-
def _ndarray_values(self):
492+
def _ndarray_values(self) -> np.ndarray:
491493
return self.codes
492494

493495
@property
494-
def _constructor(self):
496+
def _constructor(self) -> Type["Categorical"]:
495497
return Categorical
496498

497499
@classmethod
@@ -502,15 +504,15 @@ def _formatter(self, boxed=False):
502504
# Defer to CategoricalFormatter's formatter.
503505
return None
504506

505-
def copy(self):
507+
def copy(self) -> "Categorical":
506508
"""
507509
Copy constructor.
508510
"""
509511
return self._constructor(
510512
values=self._codes.copy(), dtype=self.dtype, fastpath=True
511513
)
512514

513-
def astype(self, dtype, copy=True):
515+
def astype(self, dtype: Dtype, copy: bool = True) -> ArrayLike:
514516
"""
515517
Coerce this type to another dtype
516518
@@ -523,6 +525,8 @@ def astype(self, dtype, copy=True):
523525
object is returned.
524526
"""
525527
if is_categorical_dtype(dtype):
528+
dtype = cast(Union[str, CategoricalDtype], dtype)
529+
526530
# GH 10696/18593
527531
dtype = self.dtype.update_dtype(dtype)
528532
self = self.copy() if copy else self
@@ -532,27 +536,27 @@ def astype(self, dtype, copy=True):
532536
return np.array(self, dtype=dtype, copy=copy)
533537

534538
@cache_readonly
535-
def ndim(self):
539+
def ndim(self) -> int:
536540
"""
537541
Number of dimensions of the Categorical
538542
"""
539543
return self._codes.ndim
540544

541545
@cache_readonly
542-
def size(self):
546+
def size(self) -> int:
543547
"""
544548
return the len of myself
545549
"""
546550
return len(self)
547551

548552
@cache_readonly
549-
def itemsize(self):
553+
def itemsize(self) -> int:
550554
"""
551555
return the size of a single category
552556
"""
553557
return self.categories.itemsize
554558

555-
def tolist(self):
559+
def tolist(self) -> list:
556560
"""
557561
Return a list of the values.
558562
@@ -565,7 +569,7 @@ def tolist(self):
565569
to_list = tolist
566570

567571
@property
568-
def base(self):
572+
def base(self) -> None:
569573
"""
570574
compat, we are always our own object
571575
"""
@@ -773,7 +777,7 @@ def _set_categories(self, categories, fastpath=False):
773777

774778
self._dtype = new_dtype
775779

776-
def _set_dtype(self, dtype):
780+
def _set_dtype(self, dtype: CategoricalDtype) -> "Categorical":
777781
"""
778782
Internal method for directly updating the CategoricalDtype
779783

pandas/core/dtypes/dtypes.py

+8-5
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
""" define extension dtypes """
22
import re
3-
from typing import Any, Dict, List, Optional, Tuple, Type, Union
3+
from typing import Any, Dict, List, Optional, Tuple, Type, Union, cast
44
import warnings
55

66
import numpy as np
@@ -11,6 +11,8 @@
1111

1212
from pandas.core.dtypes.generic import ABCCategoricalIndex, ABCDateOffset, ABCIndexClass
1313

14+
from pandas._typing import OrderedType
15+
1416
from .base import ExtensionDtype
1517
from .inference import is_bool, is_list_like
1618

@@ -20,9 +22,6 @@
2022
# CategoricalDtype constructor to detect when ordered=None is explicitly passed
2123
ordered_sentinel = object() # type: object
2224

23-
# TODO(GH26403): Replace with Optional[bool] or bool
24-
OrderedType = Union[None, bool, object]
25-
2625

2726
def register_extension_dtype(cls: Type[ExtensionDtype],) -> Type[ExtensionDtype]:
2827
"""
@@ -529,7 +528,9 @@ def validate_categories(categories, fastpath: bool = False):
529528

530529
return categories
531530

532-
def update_dtype(self, dtype: "CategoricalDtype") -> "CategoricalDtype":
531+
def update_dtype(
532+
self, dtype: Union[str_type, "CategoricalDtype"]
533+
) -> "CategoricalDtype":
533534
"""
534535
Returns a CategoricalDtype with categories and ordered taken from dtype
535536
if specified, otherwise falling back to self if unspecified
@@ -552,6 +553,8 @@ def update_dtype(self, dtype: "CategoricalDtype") -> "CategoricalDtype":
552553
).format(dtype=dtype)
553554
raise ValueError(msg)
554555

556+
dtype = cast(CategoricalDtype, dtype)
557+
555558
# dtype is CDT: keep current categories/ordered if None
556559
new_categories = dtype.categories
557560
if new_categories is None:

0 commit comments

Comments
 (0)