Skip to content

Commit 7e1f944

Browse files
authored
BUG: add a special case for StringDType in np.isdtype (numpy#32030)
1 parent b0401b6 commit 7e1f944

2 files changed

Lines changed: 33 additions & 0 deletions

File tree

‎numpy/_core/numerictypes.py‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -81,6 +81,7 @@
8181
from numpy._utils import set_module
8282

8383
from . import multiarray as ma
84+
from ._multiarray_umath import StringDType
8485
from .multiarray import (
8586
busday_count,
8687
busday_offset,
@@ -311,9 +312,15 @@ def _preprocess_dtype(dtype):
311312
1. fetching type from a data type
312313
2. verifying that types are built-in NumPy dtypes
313314
"""
315+
orig_dtype = dtype
314316
if isinstance(dtype, ma.dtype):
315317
dtype = dtype.type
316318
if isinstance(dtype, ndarray) or dtype not in allTypes.values():
319+
if isinstance(orig_dtype, StringDType) or orig_dtype is StringDType:
320+
# StringDType's scalar type is the builtin `str`, which is not
321+
# a NumPy scalar type, so use the DType class to identify it.
322+
# if we ever fix gh-28165, this should be deleted
323+
return StringDType
317324
raise _PreprocessDTypeError
318325
return dtype
319326

‎numpy/_core/tests/test_numerictypes.py‎

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -470,6 +470,32 @@ def test_isdtype_invalid_args(self):
470470
with assert_raises_regex(ValueError, r".*not a known kind name.*"):
471471
np.isdtype(np.int64, "int64")
472472

473+
def test_isdtype_string_dtype(self):
474+
# gh-27545: StringDType has no NumPy scalar type, but it is a
475+
# built-in dtype, so `isdtype` must accept it rather than raise
476+
dt = np.dtypes.StringDType()
477+
assert not np.isdtype(dt, "bool")
478+
for kind in self.dtype_group_dict:
479+
assert not np.isdtype(dt, kind)
480+
481+
# matches itself and the StringDType class, which stands in for
482+
# the scalar type that identifies the other dtypes
483+
assert np.isdtype(dt, dt)
484+
assert np.isdtype(dt, np.dtypes.StringDType)
485+
assert np.isdtype(np.dtypes.StringDType, dt)
486+
assert np.isdtype(dt, ("numeric", np.dtypes.StringDType))
487+
assert not np.isdtype(np.int64, dt)
488+
assert not np.isdtype(dt, ("integral", np.int64))
489+
490+
# dtype parameters are ignored, like datetime64 units
491+
assert np.isdtype(np.dtypes.StringDType(na_object=None), dt)
492+
assert np.isdtype(dt, np.dtypes.StringDType(na_object=np.nan,
493+
coerce=False))
494+
495+
# fixed-width unicode strings are a different kind
496+
assert not np.isdtype(dt, np.str_)
497+
assert not np.isdtype(np.dtype("U8"), dt)
498+
473499
def test_sctypes_complete(self):
474500
# issue 26439: int32/intc were masking each other on 32-bit builds
475501
assert np.int32 in sctypes['int']

0 commit comments

Comments
 (0)