8000 Merge pull request #371 from rlamy/bytes-pickle · numpy/numpy@fd15162 · GitHub
[go: up one dir, main page]

Skip to content

Commit fd15162

Browse files
committed
Merge pull request #371 from rlamy/bytes-pickle
Copy bytes object for small arrays when unpickling an array
2 parents 26fed25 + d183928 commit fd15162

File tree

2 files changed

+11
-2
lines changed

2 files changed

+11
-2
lines changed

numpy/core/src/multiarray/methods.c

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1587,8 +1587,9 @@ array_setstate(PyArrayObject *self, PyObject *args)
15871587
/* Check that the string is not interned */
15881588
if (!_IsAligned(self) || swap || PyString_CHECK_INTERNED(rawdata)) {
15891589
#else
1590-
/* Bytes are never interned */
1591-
if (!_IsAligned(self) || swap) {
1590+
/* Bytes should always be considered immutable, but we just grab the
1591+
* pointer if they are large, to save memory. */
1592+
if (!_IsAligned(self) || swap || (len <= 1000)) {
15921593
#endif
15931594
npy_intp num = PyArray_NBYTES(self);
15941595
fa->data = PyDataMem_NEW(num);

numpy/core/tests/test_regression.py

Original file line numberDiff line numberDiff line change
@@ -1601,6 +1601,14 @@ def test_pickle_string_overwrite(self):
16011601
s = re.sub("a(.)", "\x01\\1", "a_")
16021602
assert_equal(s[0], "\x01")
16031603

1604+
def test_pickle_bytes_overwrite(self):
1605+
if sys.version_info[0] >= 3:
1606+
data = np.array([1], dtype='b')
1607+
data = pickle.loads(pickle.dumps(data))
1608+
data[0] = 0xdd
1609+
bytestring = "\x01 ".encode('ascii')
1610+
assert_equal(bytestring[0:1], '\x01'.encode('ascii'))
1611+
16041612
def test_structured_type_to_object(self):
16051613
a_rec = np.array([(0,1), (3,2)], dtype='i4,i8')
16061614
a_obj = np.empty((2,), dtype=object)

0 commit comments

Comments
 (0)
0