[issue43097] IndexError msg of random.choice() not helpful
Raymond Hettinger
report at bugs.python.org
Tue Feb 2 08:25:33 EST 2021
Raymond Hettinger <raymond.hettinger at gmail.com> added the comment:
-1 on changing this because we would have to gum-up and slow down the code with an extra try-except to catch and reraise the exception with a different error message:
def choice(self, seq):
"""Choose a random element from a non-empty sequence."""
try:
return seq[self._randbelow(len(seq))]
except IndexError:
raise IndexError('Cannot choose from an empty sequence') from None
We rarely do that elsewhere in the code. The norm in pure python code is that indexing into an empty list shows "IndexError: list index out of range" without further elaboration on what it means for the list to be empty.
FWIW, this behavior is very old and doesn't seem to have been a problem in practice. Here is what the code looked like in Python 2.1:
def choice(self, seq):
"""Choose a random element from a non-empty sequence."""
return seq[int(self.random() * len(seq))]
----------
_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue43097>
_______________________________________
More information about the Python-bugs-list
mailing list