]> granicus.if.org Git - python/commitdiff
Fix corner case for Random.choice() and add tests.
authorRaymond Hettinger <python@rcn.com>
Tue, 7 Sep 2010 10:06:56 +0000 (10:06 +0000)
committerRaymond Hettinger <python@rcn.com>
Tue, 7 Sep 2010 10:06:56 +0000 (10:06 +0000)
Lib/random.py
Lib/test/test_random.py

index 88b8f6d701c04212f2b18edb6b5df50815338c12..0886562a2148c0bf9eaaee7734a16722d9fc7584 100644 (file)
@@ -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.
index f5c0030b190fc6b984cda70e24be4ec93761b71d..08edeaddaa79a65d45a52f5b6c679326f3a377f8 100644 (file)
@@ -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