]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
GH-100805: Support numpy.array() in random.choice(). (GH-100830)
authorMiss Islington (bot) <31488909+miss-islington@users.noreply.github.com>
Sun, 8 Jan 2023 20:04:49 +0000 (12:04 -0800)
committerGitHub <noreply@github.com>
Sun, 8 Jan 2023 20:04:49 +0000 (12:04 -0800)
(cherry picked from commit 9a68ff12c3e647a4f8dd935919ae296593770a6b)

Co-authored-by: Raymond Hettinger <rhettinger@users.noreply.github.com>
Lib/random.py
Lib/test/test_random.py
Misc/NEWS.d/next/Library/2023-01-07-15-13-47.gh-issue-100805.05rBz9.rst [new file with mode: 0644]

index f94616e048c554a5c0f92d543386b159d6f76a1b..22dcb4d3991c6340dc3c177ad4beb13f86bfcd08 100644 (file)
@@ -366,7 +366,10 @@ class Random(_random.Random):
 
     def choice(self, seq):
         """Choose a random element from a non-empty sequence."""
-        if not seq:
+
+        # As an accommodation for NumPy, we don't use "if not seq"
+        # because bool(numpy.array()) raises a ValueError.
+        if not len(seq):
             raise IndexError('Cannot choose from an empty sequence')
         return seq[self._randbelow(len(seq))]
 
index 32e7868ba4de7602b9efae9e89e9c98ffa617de3..f32d592ce815e85e389f3220ed4b244996bd19ce 100644 (file)
@@ -111,6 +111,21 @@ class TestBasicOps:
         self.assertEqual(choice([50]), 50)
         self.assertIn(choice([25, 75]), [25, 75])
 
+    def test_choice_with_numpy(self):
+        # Accommodation for NumPy arrays which have disabled __bool__().
+        # See: https://github.com/python/cpython/issues/100805
+        choice = self.gen.choice
+
+        class NA(list):
+            "Simulate numpy.array() behavior"
+            def __bool__(self):
+                raise RuntimeError
+
+        with self.assertRaises(IndexError):
+            choice(NA([]))
+        self.assertEqual(choice(NA([50])), 50)
+        self.assertIn(choice(NA([25, 75])), [25, 75])
+
     def test_sample(self):
         # For the entire allowable range of 0 <= k <= N, validate that
         # the sample is of the correct length and contains only unique items
diff --git a/Misc/NEWS.d/next/Library/2023-01-07-15-13-47.gh-issue-100805.05rBz9.rst b/Misc/NEWS.d/next/Library/2023-01-07-15-13-47.gh-issue-100805.05rBz9.rst
new file mode 100644 (file)
index 0000000..4424d7c
--- /dev/null
@@ -0,0 +1,2 @@
+Modify :func:`random.choice` implementation to once again work with NumPy
+arrays.