Skip to content

Commit 8ac7ac9

Browse files
vrakeshseberg
authored andcommitted
ENH: Raise TypeError on concat for np.array
Note that this is a Python implementation detail and *not* a language standard. Users should not rely on the error being set, as it may not be set e.g. on PyPy. (See gh-16570 for discussion, this has been briefly discussed on Python as well: https://mail.python.org/archives/list/python-dev@python.org/message/HCXMI7LPWZEKKPRIJTVHN5ZRWIUXM5C3/ Fixes gh-16489
1 parent 7cbd822 commit 8ac7ac9

File tree

2 files changed

+30
-2
lines changed

2 files changed

+30
-2
lines changed

numpy/core/src/multiarray/sequence.c

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -50,9 +50,24 @@ array_contains(PyArrayObject *self, PyObject *el)
5050
return ret;
5151
}
5252

53+
static PyObject *
54+
array_concat(PyObject *self, PyObject *other)
55+
{
56+
/*
57+
* Throw a type error, when trying to concat NDArrays
58+
* NOTE: This error is not Thrown when running with PyPy
59+
*/
60+
PyErr_SetString(PyExc_TypeError,
61+
"Concatenation operation is not implemented for NumPy arrays, "
62+
"use np.concatenate() instead. Please do not rely on this error; "
63+
"it may not be given on all Python implementations.");
64+
return NULL;
65+
}
66+
67+
5368
NPY_NO_EXPORT PySequenceMethods array_as_sequence = {
5469
(lenfunc)array_length, /*sq_length*/
55-
(binaryfunc)NULL, /*sq_concat is handled by nb_add*/
70+
(binaryfunc)array_concat, /*sq_concat for operator.concat*/
5671
(ssizeargfunc)NULL,
5772
(ssizeargfunc)array_item,
5873
(ssizessizeargfunc)NULL,

numpy/core/tests/test_shape_base.py

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88
_block_concatenate, _block_slicing)
99
from numpy.testing import (
1010
assert_, assert_raises, assert_array_equal, assert_equal,
11-
assert_raises_regex, assert_warns
11+
assert_raises_regex, assert_warns, IS_PYPY
1212
)
1313

1414

@@ -320,6 +320,19 @@ def test_concatenate(self):
320320
assert_(out is rout)
321321
assert_equal(res, rout)
322322

323+
@pytest.mark.skipif(IS_PYPY, reason="PYPY handles sq_concat, nb_add differently than cpython")
324+
def test_operator_concat(self):
325+
import operator
326+
a = array([1, 2])
327+
b = array([3, 4])
328+
n = [1,2]
329+
res = array([1, 2, 3, 4])
330+
assert_raises(TypeError, operator.concat, a, b)
331+
assert_raises(TypeError, operator.concat, a, n)
332+
assert_raises(TypeError, operator.concat, n, a)
333+
assert_raises(TypeError, operator.concat, a, 1)
334+
assert_raises(TypeError, operator.concat, 1, a)
335+
323336
def test_bad_out_shape(self):
324337
a = array([1, 2])
325338
b = array([3, 4])

0 commit comments

Comments
 (0)