summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorRaymond Hettinger <python@rcn.com>2010-09-07 10:06:56 (GMT)
committerRaymond Hettinger <python@rcn.com>2010-09-07 10:06:56 (GMT)
commitdc4872eefe2531e6627aa09818e95372a50e3b45 (patch)
tree0b61130e5de9917744671797d0ffab1b2036898c
parentc324697bac35d7151c93f3c64009b3ec17a053e7 (diff)
downloadcpython-dc4872eefe2531e6627aa09818e95372a50e3b45.zip
cpython-dc4872eefe2531e6627aa09818e95372a50e3b45.tar.gz
cpython-dc4872eefe2531e6627aa09818e95372a50e3b45.tar.bz2
Fix corner case for Random.choice() and add tests.
-rw-r--r--Lib/random.py6
-rw-r--r--Lib/test/test_random.py7
2 files changed, 12 insertions, 1 deletions
diff --git a/Lib/random.py b/Lib/random.py
index 88b8f6d..0886562 100644
--- a/Lib/random.py
+++ b/Lib/random.py
@@ -239,7 +239,11 @@ class Random(_random.Random):
def choice(self, seq):
"""Choose a random element from a non-empty sequence."""
- return seq[self._randbelow(len(seq))] # raises IndexError if seq is empty
+ try:
+ i = self._randbelow(len(seq))
+ except ValueError:
+ raise IndexError('Cannot choose from an empty sequence')
+ return seq[i]
def shuffle(self, x, random=None, int=int):
"""x, random=random.random -> shuffle list x in place; return None.
diff --git a/Lib/test/test_random.py b/Lib/test/test_random.py
index f5c0030..08edead 100644
--- a/Lib/test/test_random.py
+++ b/Lib/test/test_random.py
@@ -42,6 +42,13 @@ class TestBasicOps(unittest.TestCase):
self.assertRaises(TypeError, self.gen.seed, 1, 2, 3, 4)
self.assertRaises(TypeError, type(self.gen), [])
+ def test_choice(self):
+ choice = self.gen.choice
+ with self.assertRaises(IndexError):
+ choice([])
+ self.assertEqual(choice([50]), 50)
+ self.assertIn(choice([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