Skip to content

Commit e25af93

Browse files
miss-islingtonWolfgang Maier
authored andcommitted
bpo-33203: Ensure random.choice always raises IndexError on empty sequence (GH-6338) (GH-6388)
(cherry picked from commit 091e95e) Co-authored-by: Wolfgang Maier <wolfgang.maier@biologie.uni-freiburg.de>
1 parent 29bc6f6 commit e25af93

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
@@ -241,6 +241,8 @@ def _randbelow(self, n, int=int, maxsize=1<<BPF, type=type,
241241
"enough bits to choose from a population range this large.\n"
242242
"To remove the range limitation, add a getrandbits() method.")
243243
return int(random() * n)
244+
if n == 0:
245+
raise ValueError("Boundary cannot be zero")
244246
rem = maxsize % n
245247
limit = (maxsize - rem) / maxsize # int(limit * maxsize) % n == 0
246248
r = random()

Lib/test/test_random.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -644,7 +644,10 @@ def test_randbelow_overridden_random(self, random_mock):
644644
# Population range too large (n >= maxsize)
645645
self.gen._randbelow(maxsize+1, maxsize = maxsize)
646646
self.gen._randbelow(5640, maxsize = maxsize)
647-
647+
# issue 33203: test that _randbelow raises ValueError on
648+
# n == 0 also in its getrandbits-independent branch.
649+
with self.assertRaises(ValueError):
650+
self.gen._randbelow(0, maxsize=maxsize)
648651
# This might be going too far to test a single line, but because of our
649652
# noble aim of achieving 100% test coverage we need to write a case in
650653
# 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)