Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

BUG: fix incorrect bytes to stringdtype coercion #28282

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鈥檒l occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Feb 5, 2025
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
9 changes: 9 additions & 0 deletions 9 numpy/_core/src/multiarray/stringdtype/dtype.c
Original file line number Diff line number Diff line change
Expand Up @@ -270,6 +270,15 @@ as_pystring(PyObject *scalar, int coerce)
"string coercion is disabled.");
return NULL;
}
else if (scalar_type == &PyBytes_Type) {
// assume UTF-8 encoding
char *buffer;
Py_ssize_t length;
if (PyBytes_AsStringAndSize(scalar, &buffer, &length) < 0) {
return NULL;
}
return PyUnicode_FromStringAndSize(buffer, length);
}
else {
// attempt to coerce to str
scalar = PyObject_Str(scalar);
Expand Down
14 changes: 13 additions & 1 deletion 14 numpy/_core/tests/test_stringdtype.py
Original file line number Diff line number Diff line change
Expand Up @@ -190,10 +190,14 @@ def test_array_creation_utf8(dtype, data):
],
)
def test_scalars_string_conversion(data, dtype):
try:
str_vals = [str(d.decode('utf-8')) for d in data]
except AttributeError:
str_vals = [str(d) for d in data]
if dtype.coerce:
assert_array_equal(
np.array(data, dtype=dtype),
np.array([str(d) for d in data], dtype=dtype),
np.array(str_vals, dtype=dtype),
)
else:
with pytest.raises(ValueError):
Expand Down Expand Up @@ -284,6 +288,14 @@ def test_bytes_casts(self, dtype, strings):
barr = np.array(utf8_bytes, dtype=bytes_dtype)
assert_array_equal(barr, sarr.astype(bytes_dtype))
assert_array_equal(barr.astype(dtype), sarr)
if dtype.coerce:
barr = np.array(utf8_bytes, dtype=dtype)
assert_array_equal(barr, sarr)
barr = np.array(utf8_bytes, dtype="O")
assert_array_equal(barr.astype(dtype), sarr)
else:
with pytest.raises(ValueError):
np.array(utf8_bytes, dtype=dtype)
except UnicodeEncodeError:
with pytest.raises(UnicodeEncodeError):
sarr.astype("S20")
Expand Down
Loading
Morty Proxy This is a proxified and sanitized view of the page, visit original site.