diff --git a/Lib/test/test_array.py b/Lib/test/test_array.py --- a/Lib/test/test_array.py +++ b/Lib/test/test_array.py @@ -1026,6 +1026,18 @@ basesize = support.calcvobjsize('Pn2Pi') support.check_sizeof(self, a, basesize) + def test_initialize_with_unicode(self): + if self.typecode != 'u': + with self.assertRaises(TypeError) as cm: + a = array.array(self.typecode, 'foo') + self.assertIn("cannot use a str", str(cm.exception)) + with self.assertRaises(TypeError) as cm: + a = array.array(self.typecode, array.array('u', 'foo')) + self.assertIn("cannot use a unicode array", str(cm.exception)) + else: + a = array.array(self.typecode, "foo") + a = array.array(self.typecode, array.array('u', 'foo')) + class StringTest(BaseTest): diff --git a/Modules/arraymodule.c b/Modules/arraymodule.c --- a/Modules/arraymodule.c +++ b/Modules/arraymodule.c @@ -2484,6 +2484,20 @@ if (!PyArg_ParseTuple(args, "C|O:array", &c, &initial)) return NULL; + if (initial && c != 'u') { + if (PyUnicode_Check(initial)) { + PyErr_Format(PyExc_TypeError, "cannot use a str to initialize " + "an array with typecode '%c'", c); + return NULL; + } + else if (array_Check(initial) && + ((arrayobject*)initial)->ob_descr->typecode == 'u') { + PyErr_Format(PyExc_TypeError, "cannot use a unicode array to " + "initialize an array with typecode '%c'", c); + return NULL; + } + } + if (!(initial == NULL || PyList_Check(initial) || PyByteArray_Check(initial) || PyBytes_Check(initial)