mirror of https://github.com/python/cpython
GH-100805: Support numpy.array() in random.choice(). (GH-100830)
This commit is contained in:
parent
87d3bd0e02
commit
9a68ff12c3
|
@ -336,7 +336,10 @@ class Random(_random.Random):
|
||||||
|
|
||||||
def choice(self, seq):
|
def choice(self, seq):
|
||||||
"""Choose a random element from a non-empty sequence."""
|
"""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')
|
raise IndexError('Cannot choose from an empty sequence')
|
||||||
return seq[self._randbelow(len(seq))]
|
return seq[self._randbelow(len(seq))]
|
||||||
|
|
||||||
|
|
|
@ -111,6 +111,21 @@ class TestBasicOps:
|
||||||
self.assertEqual(choice([50]), 50)
|
self.assertEqual(choice([50]), 50)
|
||||||
self.assertIn(choice([25, 75]), [25, 75])
|
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):
|
def test_sample(self):
|
||||||
# For the entire allowable range of 0 <= k <= N, validate that
|
# For the entire allowable range of 0 <= k <= N, validate that
|
||||||
# the sample is of the correct length and contains only unique items
|
# the sample is of the correct length and contains only unique items
|
||||||
|
|
|
@ -0,0 +1,2 @@
|
||||||
|
Modify :func:`random.choice` implementation to once again work with NumPy
|
||||||
|
arrays.
|
Loading…
Reference in New Issue