Skip to content

Commit db6a300

Browse files
committed
BUG: Avoid TypeError in numpy.issubdtype when uninterpretable input type
As reported in #28946, `numpy.issubdtype` raises TypeError when given uninterpretable type. This commit adds try-except guard to handle such cases.
1 parent 9a1fd19 commit db6a300

File tree

2 files changed

+14
-4
lines changed

2 files changed

+14
-4
lines changed

numpy/_core/numerictypes.py

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -530,10 +530,15 @@ def issubdtype(arg1, arg2):
530530
True
531531
532532
"""
533-
if not issubclass_(arg1, generic):
534-
arg1 = dtype(arg1).type
535-
if not issubclass_(arg2, generic):
536-
arg2 = dtype(arg2).type
533+
try:
534+
if not issubclass_(arg1, generic):
535+
arg1 = dtype(arg1).type
536+
if not issubclass_(arg2, generic):
537+
arg2 = dtype(arg2).type
538+
except TypeError:
539+
# If either arg1 or arg2 cannot be casted to dtype object,
540+
# they are not subdtype. (See #-28946)
541+
return False
537542

538543
return issubclass(arg1, arg2)
539544

numpy/_core/tests/test_numerictypes.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33

44
import pytest
55

6+
from typing import Union
67
import numpy as np
78
import numpy._core.numerictypes as nt
89
from numpy._core.numerictypes import issctype, maximum_sctype, sctype2char, sctypes
@@ -407,6 +408,10 @@ def test_nondtype_nonscalartype(self):
407408
assert not np.issubdtype(np.float32, "float")
408409
assert not np.issubdtype(np.float64, "f")
409410

411+
# Some type cannot be interpreted by numpy
412+
assert not np.issubdtype(Union[str, int], np.number)
413+
assert not np.issubdtype(np.number, Union[str, int, float])
414+
410415
# Test the same for the correct first datatype and abstract one
411416
# in the case of int, float, complex:
412417
assert np.issubdtype(np.float64, 'float64')

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy