Skip to content

Commit baf304e

Browse files
miss-islingtonWolfgang Maier
authored andcommitted
bpo-33203: Ensure random.choice always raises IndexError on empty sequence (GH-6338) (GH-6387)
(cherry picked from commit 091e95e) Co-authored-by: Wolfgang Maier <[email protected]>
1 parent 83f564f commit baf304e

File tree

3 files changed

+9
-1
lines changed

3 files changed

+9
-1
lines changed

Lib/random.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -242,6 +242,8 @@ def _randbelow(self, n, int=int, maxsize=1<<BPF, type=type,
242242
"enough bits to choose from a population range this large.\n"
243243
"To remove the range limitation, add a getrandbits() method.")
244244
return int(random() * n)
245+
if n == 0:
246+
raise ValueError("Boundary cannot be zero")
245247
rem = maxsize % n
246248
limit = (maxsize - rem) / maxsize # int(limit * maxsize) % n == 0
247249
r = random()

Lib/test/test_random.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -651,7 +651,10 @@ def test_randbelow_overridden_random(self, random_mock):
651651
# Population range too large (n >= maxsize)
652652
self.gen._randbelow(maxsize+1, maxsize = maxsize)
653653
self.gen._randbelow(5640, maxsize = maxsize)
654-
654+
# issue 33203: test that _randbelow raises ValueError on
655+
# n == 0 also in its getrandbits-independent branch.
656+
with self.assertRaises(ValueError):
657+
self.gen._randbelow(0, maxsize=maxsize)
655658
# This might be going too far to test a single line, but because of our
656659
# noble aim of achieving 100% test coverage we need to write a case in
657660
# which the following line in Random._randbelow() gets executed:
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
``random.Random.choice()`` now raises ``IndexError`` for empty sequences
2+
consistently even when called from subclasses without a ``getrandbits()``
3+
implementation.

0 commit comments

Comments
 (0)