Skip to content

Commit

Permalink
bpo-33203: Ensure random.choice always raises IndexError on empty seq…
Browse files Browse the repository at this point in the history
…uence (GH-6338)
  • Loading branch information
Wolfgang Maier authored and rhettinger committed Apr 5, 2018
1 parent 7494091 commit 091e95e
Show file tree
Hide file tree
Showing 3 changed files with 9 additions and 1 deletion.
2 changes: 2 additions & 0 deletions Lib/random.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down
5 changes: 4 additions & 1 deletion Lib/test/test_random.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
``random.Random.choice()`` now raises ``IndexError`` for empty sequences
consistently even when called from subclasses without a ``getrandbits()``
implementation.

0 comments on commit 091e95e

Please sign in to comment.