Skip to content

BUG: numpy.result_type: drop the width of fixed-width dtypes when combined with python str / bytes #27546

@keewis

Description

@keewis

Describe the issue:

numpy.result_dtype currently returns a dtype with length information when combining concrete fixed-width dtypes with their variable-length python equivalent:

np.result_type(np.dtype("<U4"), str)  # np.dtype("<U4")
np.result_type(np.dtype("S3"), bytes)  # np.dtype("S3")

I would argue that in this specific case result_type should instead drop the length information (i.e. return np.dtype("<U") and np.dtype("S")), since the python string may be longer than the current length of the dtype.

Obviously, for new code the new string dtype will not have this issue and should be preferred, but this concerns code that tries to be compatible with both (in my case, xarray).

cc @shoyer

Reproduce the code example:

import numpy as np

result = np.result_type(np.dtype("<U3"), str)
assert result == np.dtype("<U")  # assertion error

Error message:

No response

Python and NumPy Versions:

2.1.1
3.12.6 | packaged by conda-forge | (main, Sep 22 2024, 14:16:49) [GCC 13.3.0]

Runtime Environment:

No response

Context for the issue:

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    00 - Bug57 - Close?Issues which may be closable unless discussion continued

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions