Index: Objects/bytearrayobject.c =================================================================== --- Objects/bytearrayobject.c (revision 67249) +++ Objects/bytearrayobject.c (working copy) @@ -1423,7 +1423,7 @@ { register char *input, *output; register const char *table; - register Py_ssize_t i, c, changed = 0; + register Py_ssize_t i, c; PyObject *input_obj = (PyObject*)self; const char *output_start; Py_ssize_t inlen; @@ -1469,15 +1469,7 @@ /* If no deletions are required, use faster code */ for (i = inlen; --i >= 0; ) { c = Py_CHARMASK(*input++); - if (Py_CHARMASK((*output++ = table[c])) != c) - changed = 1; } - if (changed || !PyByteArray_CheckExact(input_obj)) - goto done; - Py_DECREF(result); - Py_INCREF(input_obj); - result = input_obj; - goto done; } for (i = 0; i < 256; i++) @@ -1491,14 +1483,7 @@ if (trans_table[c] != -1) if (Py_CHARMASK(*output++ = (char)trans_table[c]) == c) continue; - changed = 1; } - if (!changed && PyByteArray_CheckExact(input_obj)) { - Py_DECREF(result); - Py_INCREF(input_obj); - result = input_obj; - goto done; - } /* Fix the size of the resulting string */ if (inlen > 0) PyByteArray_Resize(result, output - output_start); @@ -1526,15 +1511,10 @@ !memcmp(target+offset+1, pattern+1, length-2) ) -/* Bytes ops must return a string. */ -/* If the object is subclass of bytes, create a copy */ +/* Bytes ops must return a string, create a copy */ Py_LOCAL(PyByteArrayObject *) return_self(PyByteArrayObject *self) { - if (PyByteArray_CheckExact(self)) { - Py_INCREF(self); - return (PyByteArrayObject *)self; - } return (PyByteArrayObject *)PyByteArray_FromStringAndSize( PyByteArray_AS_STRING(self), PyByteArray_GET_SIZE(self)); Index: Lib/test/test_bytes.py =================================================================== --- Lib/test/test_bytes.py (revision 67249) +++ Lib/test/test_bytes.py (working copy) @@ -721,6 +721,15 @@ b.insert(0, Indexable(ord('A'))) self.assertEqual(b, b'A') + def test_copied(self): + # Make sure that operations that don't mutate the array copy the bytes. + b = bytearray(b'abc') + #self.assertFalse(b is b.replace(b'abc', b'cde', 0)) + + t = bytearray([i for i in range(256)]) + x = bytearray(b'') + self.assertFalse(x is x.translate(t)) + def test_partition_bytearray_doesnt_share_nullstring(self): a, b, c = bytearray(b"x").partition(b"y") self.assertEqual(b, b"")