This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

classification
Title: Misleading error message in random.choice
Type: Stage:
Components: Library (Lib) Versions: Python 2.4
process
Status: closed Resolution: wont fix
Dependencies: Superseder:
Assigned To: rhettinger Nosy List: nejucomo, rhettinger, tim.peters
Priority: normal Keywords:

Created on 2004-09-22 23:48 by nejucomo, last changed 2022-04-11 14:56 by admin. This issue is now closed.

Messages (5)
msg22525 - (view) Author: Nefarious CodeMonkey, Jr. (nejucomo) Date: 2004-09-22 23:48
Giving random.choice(seq) an empty sequence leads to a
misleading error message, as per this example:

>>> import random; random.choice([])
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "/usr/lib/python2.3/random.py", line 231, in choice
    return seq[int(self.random() * len(seq))]
IndexError: list index out of range


A simple fix is to "assert len(seq) > 0" in the choice
method.
msg22526 - (view) Author: Raymond Hettinger (rhettinger) * (Python committer) Date: 2004-09-23 00:05
Logged In: YES 
user_id=80475

Perhaps I've been using it for too long, but I do not find
the error message to misleading.  Also, I like having this
method as simple and lightweight as possible though it may
be worthwhile to add a line to the docs, "If the sequence is
emtpy, raises a TypeError." 

If someone accepts this request, it should implemented as a
try/except rather than an assertion.  That approach would
also let you catch TypeErrors raised is the argument doesn't
define __len__ and __getitem__, for example: 
random.choice(set('abc'))

msg22527 - (view) Author: Raymond Hettinger (rhettinger) * (Python committer) Date: 2004-09-25 17:46
Logged In: YES 
user_id=80475

Tim, I'm -1 on this one.  What do you think?
msg22528 - (view) Author: Tim Peters (tim.peters) * (Python committer) Date: 2004-09-28 02:33
Logged In: YES 
user_id=31435

No, I don't want to change this either.  choice() is one of the 
few library functions where speed matters a lot, and checking 
for invalid arguments *just* to give a wordier error message 
would be a losing tradeoff because of that.  If you want to 
add a line to the docs, that's cool, but not "If the sequence 
is empty, raises TypeError".  That's a bad idea because it 
actually raises IndexError <wink>.
msg22529 - (view) Author: Raymond Hettinger (rhettinger) * (Python committer) Date: 2004-09-28 03:04
Logged In: YES 
user_id=80475

Added a line to the docs:
   Doc/lib/librandom.tex 1.38
Marking as closed.
History
Date User Action Args
2022-04-11 14:56:07adminsetgithub: 40945
2004-09-22 23:48:38nejucomocreate