[Python-checkins] bpo-33203: Ensure random.choice always raises IndexError on empty sequence (GH-6338)

Raymond Hettinger webhook-mailer at python.org
Thu Apr 5 11:19:54 EDT 2018


https://github.com/python/cpython/commit/091e95e9004b794280ab35becec2c3e30dd5e96e
commit: 091e95e9004b794280ab35becec2c3e30dd5e96e
branch: master
author: Wolfgang Maier <wolfgang.maier at biologie.uni-freiburg.de>
committer: Raymond Hettinger <rhettinger at users.noreply.github.com>
date: 2018-04-05T08:19:44-07:00
summary:

bpo-33203: Ensure random.choice always raises IndexError on empty sequence (GH-6338)

files:
A Misc/NEWS.d/next/Library/2018-04-05-11-09-45.bpo-33203.Hje9Py.rst
M Lib/random.py
M Lib/test/test_random.py

diff --git a/Lib/random.py b/Lib/random.py
index 91065b7e3037..0bc24174e13f 100644
--- a/Lib/random.py
+++ b/Lib/random.py
@@ -242,6 +242,8 @@ def _randbelow(self, n, int=int, maxsize=1<<BPF, type=type,
                 "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()
diff --git a/Lib/test/test_random.py b/Lib/test/test_random.py
index 468c4a467e5d..eee245df48a1 100644
--- a/Lib/test/test_random.py
+++ b/Lib/test/test_random.py
@@ -651,7 +651,10 @@ def test_randbelow_overridden_random(self, random_mock):
             # 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
index 000000000000..ab6d17b5d1ba
--- /dev/null
+++ b/Misc/NEWS.d/next/Library/2018-04-05-11-09-45.bpo-33203.Hje9Py.rst
@@ -0,0 +1,3 @@
+``random.Random.choice()`` now raises ``IndexError`` for empty sequences
+consistently even when called from subclasses without a ``getrandbits()``
+implementation.



More information about the Python-checkins mailing list