From 9a68ff12c3e647a4f8dd935919ae296593770a6b Mon Sep 17 00:00:00 2001 From: Raymond Hettinger Date: Sun, 8 Jan 2023 13:40:35 -0600 Subject: [PATCH] GH-100805: Support numpy.array() in random.choice(). (GH-100830) --- Lib/random.py | 5 ++++- Lib/test/test_random.py | 15 +++++++++++++++ ...2023-01-07-15-13-47.gh-issue-100805.05rBz9.rst | 2 ++ 3 files changed, 21 insertions(+), 1 deletion(-) create mode 100644 Misc/NEWS.d/next/Library/2023-01-07-15-13-47.gh-issue-100805.05rBz9.rst diff --git a/Lib/random.py b/Lib/random.py index e60b7294b6d..1c9e1a48b66 100644 --- a/Lib/random.py +++ b/Lib/random.py @@ -336,7 +336,10 @@ def randint(self, a, b): 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))] diff --git a/Lib/test/test_random.py b/Lib/test/test_random.py index 67de54c7db8..50bea7be6d5 100644 --- a/Lib/test/test_random.py +++ b/Lib/test/test_random.py @@ -111,6 +111,21 @@ def test_choice(self): 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 index 00000000000..4424d7cff21 --- /dev/null +++ b/Misc/NEWS.d/next/Library/2023-01-07-15-13-47.gh-issue-100805.05rBz9.rst @@ -0,0 +1,2 @@ +Modify :func:`random.choice` implementation to once again work with NumPy +arrays.