summaryrefslogtreecommitdiff
path: root/numpy/random/tests
diff options
context:
space:
mode:
authorSebastian Berg <sebastian@sipsolutions.net>2021-02-17 16:56:32 -0600
committerSebastian Berg <sebastian@sipsolutions.net>2021-02-22 15:12:28 -0600
commit2d975a771b88bcb4d049bbb3ea5f917694ec3524 (patch)
tree485e3c1ee89e30b8d06016f58b77fe936eaef0a7 /numpy/random/tests
parent02d508c90a214e0aeaf78b4ad41a578e267dce12 (diff)
downloadnumpy-2d975a771b88bcb4d049bbb3ea5f917694ec3524.tar.gz
BUG: Correct shuffling of objects in 1-d array likes
While introducing the buffer fixed the in-place problem years ago, running valgrind (and masked arrays) pointed out to me that without the additional `...` NumPy will unpack and repack objects leading to slightly incorrect results. MAINT: Warn about shuffle bug instead of fixing it in old random API
Diffstat (limited to 'numpy/random/tests')
-rw-r--r--numpy/random/tests/test_random.py25
1 files changed, 25 insertions, 0 deletions
diff --git a/numpy/random/tests/test_random.py b/numpy/random/tests/test_random.py
index a0c72b419..2b3b65c19 100644
--- a/numpy/random/tests/test_random.py
+++ b/numpy/random/tests/test_random.py
@@ -522,6 +522,31 @@ class TestRandomDist:
random.shuffle(values)
assert "test_random" in rec[0].filename
+ @pytest.mark.parametrize("random",
+ [np.random, np.random.RandomState(), np.random.default_rng()])
+ @pytest.mark.parametrize("use_array_like", [True, False])
+ def test_shuffle_no_object_unpacking(self, random, use_array_like):
+ class MyArr(np.ndarray):
+ pass
+
+ items = [None, np.array([3]), np.float64(3), np.array(10), np.float64(7)]
+ arr = np.array(items, dtype=object)
+ item_ids = {id(i) for i in items}
+ if use_array_like:
+ arr = arr.view(MyArr)
+
+ # The array was created fine, and did not modify any objects:
+ assert all(id(i) in item_ids for i in arr)
+
+ if use_array_like and not isinstance(random, np.random.Generator):
+ # The old API gives incorrect results, but warns about it.
+ with pytest.warns(UserWarning,
+ match="Shuffling a one dimensional array.*"):
+ random.shuffle(arr)
+ else:
+ random.shuffle(arr)
+ assert all(id(i) in item_ids for i in arr)
+
def test_shuffle_memoryview(self):
# gh-18273
# allow graceful handling of memoryviews