diff --git a/pandas/_typing.py b/pandas/_typing.py index e3b3a4774f558..abf1315f3607a 100644 --- a/pandas/_typing.py +++ b/pandas/_typing.py @@ -74,6 +74,15 @@ npt: Any = None +# Functions that take Dict/Mapping/List/Sequence/Callable as arguments can be +# tricky to type: +# - keys of Dict and Mapping cannot be sub-classes (Mapping allows them for values) +# - elements of List cannot be sub-classes (Sequence does) +# - input arguments of Callable cannot be sub-classes +# If you want to allow any type and it's sub-classes in the above cases, you can +# use TypeVar("AllowsSubclasses", bound=class); List[AllowsSubclasses] +HashableT = TypeVar("HashableT", bound=Hashable) + # array-like ArrayLike = Union["ExtensionArray", np.ndarray] @@ -127,19 +136,19 @@ Dtype = Union["ExtensionDtype", NpDtype] AstypeArg = Union["ExtensionDtype", "npt.DTypeLike"] # DtypeArg specifies all allowable dtypes in a functions its dtype argument -DtypeArg = Union[Dtype, Dict[Hashable, Dtype]] +DtypeArg = Union[Dtype, Dict[HashableT, Dtype]] DtypeObj = Union[np.dtype, "ExtensionDtype"] # converters -ConvertersArg = Dict[Hashable, Callable[[Dtype], Dtype]] +ConvertersArg = Dict[HashableT, Callable[[Dtype], Dtype]] # parse_dates ParseDatesArg = Union[ - bool, List[Hashable], List[List[Hashable]], Dict[Hashable, List[Hashable]] + bool, List[HashableT], List[List[HashableT]], Dict[HashableT, List[Hashable]] ] # For functions like rename that convert one label to another -Renamer = Union[Mapping[Hashable, Any], Callable[[Hashable], Hashable]] +Renamer = Union[Mapping[HashableT, Any], Callable[[HashableT], Hashable]] # to maintain type information across generic functions and parametrization T = TypeVar("T") @@ -156,7 +165,7 @@ # types of `func` kwarg for DataFrame.aggregate and Series.aggregate AggFuncTypeBase = Union[Callable, str] -AggFuncTypeDict = Dict[Hashable, Union[AggFuncTypeBase, List[AggFuncTypeBase]]] +AggFuncTypeDict = Dict[HashableT, Union[AggFuncTypeBase, List[AggFuncTypeBase]]] AggFuncType = Union[ AggFuncTypeBase, List[AggFuncTypeBase], @@ -260,10 +269,10 @@ def closed(self) -> bool: FormattersType = Union[ List[Callable], Tuple[Callable, ...], Mapping[Union[str, int], Callable] ] -ColspaceType = Mapping[Hashable, Union[str, int]] +ColspaceType = Mapping[HashableT, Union[str, int]] FloatFormatType = Union[str, Callable, "EngFormatter"] ColspaceArgType = Union[ - str, int, Sequence[Union[str, int]], Mapping[Hashable, Union[str, int]] + str, int, Sequence[Union[str, int]], Mapping[HashableT, Union[str, int]] ] # Arguments for fillna()