1212
1313import numpy as np
1414
15- from pandas ._config import using_string_dtype
15+ from pandas ._config import (
16+ get_option ,
17+ using_string_dtype ,
18+ )
1619
1720from pandas ._libs import (
1821 Interval ,
@@ -1793,14 +1796,36 @@ def validate_all_hashable(*args, error_name: str | None = None) -> None:
17931796 raise TypeError ("All elements must be hashable" )
17941797
17951798
1796- def pandas_dtype (dtype ) -> DtypeObj :
1799+ def _map_np_dtype (dtype : np .dtype ) -> DtypeObj :
1800+ if dtype .kind in "iu" :
1801+ from pandas .core .arrays .integer import NUMPY_INT_TO_DTYPE
1802+
1803+ return NUMPY_INT_TO_DTYPE [dtype ]
1804+ elif dtype .kind == "f" :
1805+ from pandas .core .arrays .floating import NUMPY_FLOAT_TO_DTYPE
1806+
1807+ if dtype .itemsize != 2 :
1808+ # TODO: What do we do for float16? float128?
1809+ return NUMPY_FLOAT_TO_DTYPE [dtype ]
1810+
1811+ elif dtype .kind == "b" :
1812+ from pandas import BooleanDtype
1813+
1814+ return BooleanDtype ()
1815+
1816+ return dtype
1817+
1818+
1819+ def pandas_dtype (dtype , allow_numpy_dtypes : bool = False ) -> DtypeObj :
17971820 """
17981821 Convert input into a pandas only dtype object or a numpy dtype object.
17991822
18001823 Parameters
18011824 ----------
18021825 dtype : object
18031826 The object to be converted into a dtype.
1827+ allow_numpy_dtypes : bool, default False
1828+ Whether to return pre-PDEP16 numpy dtypes for ints, floats, and bools.
18041829
18051830 Returns
18061831 -------
@@ -1820,10 +1845,18 @@ def pandas_dtype(dtype) -> DtypeObj:
18201845 >>> pd.api.types.pandas_dtype(int)
18211846 dtype('int64')
18221847 """
1848+ allow_numpy_dtypes = allow_numpy_dtypes or not get_option ("mode.pdep16_data_types" )
1849+
18231850 # short-circuit
18241851 if isinstance (dtype , np .ndarray ):
1825- return dtype .dtype
1826- elif isinstance (dtype , (np .dtype , ExtensionDtype )):
1852+ if allow_numpy_dtypes :
1853+ return dtype .dtype
1854+ return _map_np_dtype (dtype .dtype )
1855+ elif isinstance (dtype , np .dtype ):
1856+ if allow_numpy_dtypes :
1857+ return dtype
1858+ return _map_np_dtype (dtype )
1859+ elif isinstance (dtype , ExtensionDtype ):
18271860 return dtype
18281861
18291862 # builtin aliases
@@ -1879,7 +1912,9 @@ def pandas_dtype(dtype) -> DtypeObj:
18791912 elif npdtype .kind == "O" :
18801913 raise TypeError (f"dtype '{ dtype } ' not understood" )
18811914
1882- return npdtype
1915+ if allow_numpy_dtypes :
1916+ return npdtype
1917+ return _map_np_dtype (npdtype )
18831918
18841919
18851920def is_all_strings (value : ArrayLike ) -> bool :
0 commit comments