Skip to content

BUG: raise a clear error in common_type for non-array input#31592

Open
Lawson-Darrow wants to merge 1 commit into
numpy:mainfrom
Lawson-Darrow:fix/common-type-dtype-error-30890
Open

BUG: raise a clear error in common_type for non-array input#31592
Lawson-Darrow wants to merge 1 commit into
numpy:mainfrom
Lawson-Darrow:fix/common-type-dtype-error-30890

Conversation

@Lawson-Darrow

Copy link
Copy Markdown
Contributor

Fixes #30890

Summary

numpy.common_type does a.dtype.type on each input so passing a dtype or a scalar type, for example np.common_type(np.dtype("f4")), raised a confusing AttributeError ('numpy.dtypes.Float32DType' object has no attribute 'dtype').

This catches that case and raises a TypeError that points to np.result_type and np.promote_types which are the tools meant for combining dtypes and scalar types. A dtype instance is shown as dtype('float32') and a scalar type as 'float32'. Valid array inputs are unchanged. This follows the direction @ngoldbaum and @seberg suggested on the issue.

Before:

>>> np.common_type(np.dtype("f4"))
AttributeError: 'numpy.dtypes.Float32DType' object has no attribute 'dtype'

After:

>>> np.common_type(np.dtype("f4"))
TypeError: common_type takes array inputs, not dtype('float32'). To find a common type for dtypes or scalar types use np.result_type or np.promote_types instead.

Test plan

Added tests in numpy/lib/tests/test_type_check.py for dtype and scalar-type inputs: a clear TypeError with the np.result_type / np.promote_types guidance, the dtype instance shown as dtype('float32'), and the scalar type as 'float32'. Existing TestCommonType.test_basic still covers real arrays. Release note added in doc/release/upcoming_changes/30890.improvement.rst.

This change was prepared with AI assistance (Claude Code, OpenAI Codex). I reviewed and verified the change and the tests locally and take responsibility for it.

common_type does a.dtype.type on each input, so passing a dtype or a
scalar type like np.common_type(np.dtype("f4")) raised a confusing
AttributeError. Catch that case and raise a TypeError that tells the
user to reach for np.result_type or np.promote_types instead. Valid
array inputs are unchanged.

Closes numpygh-30890
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

BUG: common_type(dtype('f4'), dtype('f4')) raises AttributeError unexpectedly

1 participant