[New-bugs-announce] [issue33203] random.choice: raise IndexError on empty sequence even when not using getrandbits internally
Wolfgang Maier
report at bugs.python.org
Sun Apr 1 16:04:10 EDT 2018
New submission from Wolfgang Maier <wolfgang.maier at biologie.uni-freiburg.de>:
from https://docs.python.org/3/library/random.html#random.choice:
Return a random element from the non-empty sequence seq. If seq is empty, raises IndexError.
Indeed:
>>> import random
>>> random.choice([])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/wolma/cpython/random.py", line 259, in choice
raise IndexError('Cannot choose from an empty sequence') from None
IndexError: Cannot choose from an empty sequence
but when not using getrandbits internally:
>>> class MyRandom(random.Random):
... def random(self):
... return super().random()
...
>>> my_random=MyRandom()
>>> my_random.choice([])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/wolma/cpython/random.py", line 257, in choice
i = self._randbelow(len(seq))
File "/home/wolma/cpython/random.py", line 245, in _randbelow
rem = maxsize % n
ZeroDivisionError: integer division or modulo by zero
This is because the ValueError that random.choice tries to catch gets raised only in the getrandbits-dependent branch of Random._randbelow, but not in the branch using only Random.random (even though Random._randbelow suggests uniform behaviour.
----------
components: Library (Lib)
messages: 314787
nosy: rhettinger, serhiy.storchaka, wolma
priority: normal
severity: normal
status: open
title: random.choice: raise IndexError on empty sequence even when not using getrandbits internally
type: behavior
versions: Python 3.6, Python 3.7, Python 3.8
_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue33203>
_______________________________________
More information about the New-bugs-announce
mailing list