diff --git a/pandas/core/indexes/numeric.py b/pandas/core/indexes/numeric.py index 28144af36d6ea..2182b3647533e 100644 --- a/pandas/core/indexes/numeric.py +++ b/pandas/core/indexes/numeric.py @@ -1,6 +1,8 @@ +from __future__ import annotations + from typing import ( + Callable, Hashable, - Optional, ) import warnings @@ -49,11 +51,12 @@ class NumericIndex(Index): """ _default_dtype: np.dtype + _dtype_validation_metadata: tuple[Callable[..., bool], str] _is_numeric_dtype = True _can_hold_strings = False - def __new__(cls, data=None, dtype: Optional[Dtype] = None, copy=False, name=None): + def __new__(cls, data=None, dtype: Dtype | None = None, copy=False, name=None): name = maybe_extract_name(name, data, cls) subarr = cls._ensure_array(data, dtype, copy) @@ -97,14 +100,8 @@ def _ensure_array(cls, data, dtype, copy: bool): def _validate_dtype(cls, dtype: Dtype) -> None: if dtype is None: return - validation_metadata = { - "int64index": (is_signed_integer_dtype, "signed integer"), - "uint64index": (is_unsigned_integer_dtype, "unsigned integer"), - "float64index": (is_float_dtype, "float"), - "rangeindex": (is_signed_integer_dtype, "signed integer"), - } - - validation_func, expected = validation_metadata[cls._typ] + + validation_func, expected = cls._dtype_validation_metadata if not validation_func(dtype): raise ValueError( f"Incorrect `dtype` passed: expected {expected}, received {dtype}" @@ -264,6 +261,7 @@ class Int64Index(IntegerIndex): _typ = "int64index" _engine_type = libindex.Int64Engine _default_dtype = np.dtype(np.int64) + _dtype_validation_metadata = (is_signed_integer_dtype, "signed integer") _uint64_descr_args = { @@ -280,6 +278,7 @@ class UInt64Index(IntegerIndex): _typ = "uint64index" _engine_type = libindex.UInt64Engine _default_dtype = np.dtype(np.uint64) + _dtype_validation_metadata = (is_unsigned_integer_dtype, "unsigned integer") # ---------------------------------------------------------------- # Indexing Methods @@ -311,6 +310,7 @@ class Float64Index(NumericIndex): _typ = "float64index" _engine_type = libindex.Float64Engine _default_dtype = np.dtype(np.float64) + _dtype_validation_metadata = (is_float_dtype, "float") @property def inferred_type(self) -> str: diff --git a/pandas/core/indexes/range.py b/pandas/core/indexes/range.py index 1e974063bd839..0a2c0820f20a3 100644 --- a/pandas/core/indexes/range.py +++ b/pandas/core/indexes/range.py @@ -94,6 +94,7 @@ class RangeIndex(NumericIndex): _typ = "rangeindex" _engine_type = libindex.Int64Engine + _dtype_validation_metadata = (is_signed_integer_dtype, "signed integer") _can_hold_na = False _range: range