Skip to content

GH-100805: Support numpy.array() in random.choice(). #100830

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Jan 8, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion Lib/random.py
Original file line number Diff line number Diff line change
Expand Up @@ -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))]

Expand Down
15 changes: 15 additions & 0 deletions Lib/test/test_random.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Modify :func:`random.choice` implementation to once again work with NumPy
arrays.