[ python-Bugs-1033038 ] Misleading error message in random.choice

SourceForge.net noreply at sourceforge.net
Tue Sep 28 04:33:32 CEST 2004


Bugs item #1033038, was opened at 2004-09-22 19:48
Message generated for change (Comment added) made by tim_one
You can respond by visiting: 
https://sourceforge.net/tracker/?func=detail&atid=105470&aid=1033038&group_id=5470

Category: Python Library
Group: Python 2.4
Status: Open
Resolution: None
Priority: 5
Submitted By: Nefarious CodeMonkey, Jr. (nejucomo)
>Assigned to: Raymond Hettinger (rhettinger)
Summary: Misleading error message in random.choice

Initial Comment:
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.

----------------------------------------------------------------------

>Comment By: Tim Peters (tim_one)
Date: 2004-09-27 22:33

Message:
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>.

----------------------------------------------------------------------

Comment By: Raymond Hettinger (rhettinger)
Date: 2004-09-25 13:46

Message:
Logged In: YES 
user_id=80475

Tim, I'm -1 on this one.  What do you think?

----------------------------------------------------------------------

Comment By: Raymond Hettinger (rhettinger)
Date: 2004-09-22 20:05

Message:
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'))



----------------------------------------------------------------------

You can respond by visiting: 
https://sourceforge.net/tracker/?func=detail&atid=105470&aid=1033038&group_id=5470


More information about the Python-bugs-list mailing list