Skip to content

Fixed gh-998: exception raised while forming an expected TypeError exception message #999

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Nov 28, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 14 additions & 11 deletions dpctl/tensor/_types.pxi
Original file line number Diff line number Diff line change
Expand Up @@ -102,28 +102,29 @@ cdef str _make_typestr(int typenum):
return type_to_str[typenum] + str(type_bytesize(typenum))


cdef int typenum_from_format(str s) except *:
cdef int typenum_from_format(str s):
"""
Internal utility to convert string describing type format

Format is [<|=>][biufc]#
Shortcuts for formats are i, u, d, D
"""
if not s:
raise TypeError("Format string '" + s + "' cannot be empty.")
return -1
try:
dt = np.dtype(s)
except Exception as e:
raise TypeError("Format '" + s + "' is not understood.") from e
except Exception:
return -1
if (dt.byteorder == ">"):
raise TypeError("Format '" + s + "' can only have native byteorder.")
return -2
return dt.num


cdef int descr_to_typenum(object dtype):
"Returns typenum for argumentd dtype that has attribute descr, assumed numpy.dtype"
obj = getattr(dtype, 'descr')
if (not isinstance(obj, list) or len(obj) != 1):
return -1
return -1 # token for ValueError
obj = obj[0]
if (not isinstance(obj, tuple) or len(obj) != 2 or obj[0]):
return -1
Expand All @@ -133,7 +134,7 @@ cdef int descr_to_typenum(object dtype):
return typenum_from_format(obj)


cdef int dtype_to_typenum(dtype) except *:
cdef int dtype_to_typenum(dtype):
if isinstance(dtype, str):
return typenum_from_format(dtype)
elif isinstance(dtype, bytes):
Expand All @@ -143,9 +144,11 @@ cdef int dtype_to_typenum(dtype) except *:
else:
try:
dt = np.dtype(dtype)
if hasattr(dt, 'descr'):
return descr_to_typenum(dt)
else:
return -1
except TypeError:
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I believe except * in the definition of dtype_to_typenum isn't needed anymore also, since no exception is raised by the function.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Correct. This is an optimization change though. It does not hurt to keep it.

I will push the suggested change and merge.

return -3
except Exception:
return -1
if hasattr(dt, 'descr'):
return descr_to_typenum(dt)
else:
return -3 # token for TypeError
8 changes: 7 additions & 1 deletion dpctl/tensor/_usmarray.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -188,9 +188,15 @@ cdef class usm_ndarray:
raise TypeError("Argument shape must be a list or a tuple.")
nd = len(shape)
typenum = dtype_to_typenum(dtype)
if (typenum < 0):
if typenum == -2:
raise ValueError("Data type '" + str(dtype) + "' can only have native byteorder.")
elif typenum == -1:
raise ValueError("Data type '" + str(dtype) + "' is not understood.")
raise TypeError(f"Expected string or a dtype object, got {type(dtype)}")
itemsize = type_bytesize(typenum)
if (itemsize < 1):
raise TypeError("dtype=" + dtype + " is not supported.")
raise TypeError("dtype=" + np.dtype(dtype).name + " is not supported.")
# allocate host C-arrays for shape, strides
err = _from_input_shape_strides(
nd, shape, strides, itemsize, <char> ord(order),
Expand Down
19 changes: 17 additions & 2 deletions dpctl/tests/test_usm_ndarray_ctor.py
Original file line number Diff line number Diff line change
Expand Up @@ -95,13 +95,23 @@ def test_dtypes(dtype):
assert expected_fmt == actual_fmt


@pytest.mark.parametrize("dtype", ["", ">f4", "invalid", 123])
@pytest.mark.parametrize(
"dtype",
[
"",
">f4",
"invalid",
123,
np.dtype(">f4"),
np.dtype([("a", ">f4"), ("b", "i4")]),
],
)
def test_dtypes_invalid(dtype):
with pytest.raises((TypeError, ValueError)):
dpt.usm_ndarray((1,), dtype=dtype)


@pytest.mark.parametrize("dt", ["d", "c16"])
@pytest.mark.parametrize("dt", ["f", "c8"])
def test_properties(dt):
"""
Test that properties execute
Expand Down Expand Up @@ -1181,6 +1191,11 @@ def test_empty_like(dt, usm_kind):
assert X.sycl_queue == Y.sycl_queue


def test_empty_unexpected_data_type():
with pytest.raises(TypeError):
dpt.empty(1, dtype=np.object_)


@pytest.mark.parametrize(
"dt",
_all_dtypes,
Expand Down