]> granicus.if.org Git - python/commitdiff
bpo-33203: Ensure random.choice always raises IndexError on empty sequence (GH-6338...
authorMiss Islington (bot) <31488909+miss-islington@users.noreply.github.com>
Thu, 5 Apr 2018 16:24:27 +0000 (09:24 -0700)
committerRaymond Hettinger <rhettinger@users.noreply.github.com>
Thu, 5 Apr 2018 16:24:27 +0000 (09:24 -0700)
(cherry picked from commit 091e95e9004b794280ab35becec2c3e30dd5e96e)

Co-authored-by: Wolfgang Maier <wolfgang.maier@biologie.uni-freiburg.de>
Lib/random.py
Lib/test/test_random.py
Misc/NEWS.d/next/Library/2018-04-05-11-09-45.bpo-33203.Hje9Py.rst [new file with mode: 0644]

index 0152e5ea12bf7924e4a64184ba1b59df376b3890..7a2585e01ab3a36f154301dc36fb00809280169f 100644 (file)
@@ -241,6 +241,8 @@ class Random(_random.Random):
                 "enough bits to choose from a population range this large.\n"
                 "To remove the range limitation, add a getrandbits() method.")
             return int(random() * n)
+        if n == 0:
+            raise ValueError("Boundary cannot be zero")
         rem = maxsize % n
         limit = (maxsize - rem) / maxsize   # int(limit * maxsize) % n == 0
         r = random()
index 3e57a82b63e5435bcad391600f62eb773a57efaa..10f431a63eb75b365dacc4c135f2d50dc2b15b13 100644 (file)
@@ -644,7 +644,10 @@ class MersenneTwister_TestBasicOps(TestBasicOps, unittest.TestCase):
             # Population range too large (n >= maxsize)
             self.gen._randbelow(maxsize+1, maxsize = maxsize)
         self.gen._randbelow(5640, maxsize = maxsize)
-
+        # issue 33203: test that _randbelow raises ValueError on
+        # n == 0 also in its getrandbits-independent branch.
+        with self.assertRaises(ValueError):
+            self.gen._randbelow(0, maxsize=maxsize)
         # This might be going too far to test a single line, but because of our
         # noble aim of achieving 100% test coverage we need to write a case in
         # which the following line in Random._randbelow() gets executed:
diff --git a/Misc/NEWS.d/next/Library/2018-04-05-11-09-45.bpo-33203.Hje9Py.rst b/Misc/NEWS.d/next/Library/2018-04-05-11-09-45.bpo-33203.Hje9Py.rst
new file mode 100644 (file)
index 0000000..ab6d17b
--- /dev/null
@@ -0,0 +1,3 @@
+``random.Random.choice()`` now raises ``IndexError`` for empty sequences
+consistently even when called from subclasses without a ``getrandbits()``
+implementation.