Skip to content

MAINT: result_type cosmetic refactor #142

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 1 commit into from
Apr 2, 2025
Merged
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
34 changes: 15 additions & 19 deletions array_api_strict/_data_type_functions.py
Original file line number Diff line number Diff line change
Expand Up @@ -204,35 +204,31 @@ def result_type(
# required by the spec rather than using np.result_type. NumPy implements
# too many extra type promotions like int64 + uint64 -> float64, and does
# value-based casting on scalar arrays.
A = []
dtypes = []
scalars = []
for a in arrays_and_dtypes:
if isinstance(a, Array):
a = a.dtype
if isinstance(a, DType):
dtypes.append(a)
elif isinstance(a, Array):
dtypes.append(a.dtype)
elif isinstance(a, (bool, int, float, complex)):
scalars.append(a)
elif isinstance(a, np.ndarray) or a not in _all_dtypes:
raise TypeError("result_type() inputs must be array_api arrays or dtypes")
A.append(a)

# remove python scalars
B = [a for a in A if not isinstance(a, (bool, int, float, complex))]
else:
raise TypeError(
"result_type() inputs must be Array API arrays, dtypes, or scalars"
)

if len(B) == 0:
if not dtypes:
Copy link
Member

Choose a reason for hiding this comment

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

This got me off at a first glance, but yeah it's OK because dtypes contains both arrays and dtypes.
Is fine, even if resembles a bit a snippet I recently saw in somebody's going through the "intro to python" online course: mytuple = [].

Copy link
Contributor Author

Choose a reason for hiding this comment

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

The dtypes list contains exclusively dtypes though.

raise ValueError("at least one array or dtype is required")
elif len(B) == 1:
result = B[0]
else:
t = B[0]
for t2 in B[1:]:
t = _result_type(t, t2)
result = t
result = dtypes[0]
for t2 in dtypes[1:]:
result = _result_type(result, t2)

if len(scalars) == 0:
if not scalars:
return result

if get_array_api_strict_flags()['api_version'] <= '2023.12':
raise TypeError("result_type() inputs must be array_api arrays or dtypes")
raise TypeError("result_type() inputs must be Array API arrays or dtypes")

# promote python scalars given the result_type for all arrays/dtypes
from ._creation_functions import empty
Expand Down
Loading