New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
random.choice([]) should return more intelligible exception #40318
Comments
Python 2.3.3 (#1, Mar 31 2004, 11:17:07)
[GCC 3.2.2 20030222 (Red Hat Linux 3.2.2-5)] on linux2
Type "help", "copyright", "credits" or "license" for
more information.
>>> 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 This is simple enough here, but it's harder when it's I suggest something like ValueError: sequence must not |
Logged In: YES -0 While a ValueError would be appropriate, the status quo |
Logged In: YES I thought of that after I submitted. :-) Might it be better to raise an IndexError with a message |
Logged In: YES That's better, but I'm still -0. This function is apt to For better or worse, it is the nature of Python tracebacks I recommend closing this, but if you really think it's an |
Logged In: YES You have a point. What about rewriting the line to read: The comment would be a good hint. |
Logged In: YES Okay. Fixed. See Lib/random.py 1.61. |
Logged In: YES More succinctly: For making repeated choices, however, a generator would be def chooser(count, seq):
if type(count) not in (int, long) or count < 0:
raise ValueError('%s is not a count' % count)
try:
seqlen = len(seq)
if not seqlen: raise ValueError('Cannot choose from
nothing')
except TypeError:
raise ValueError('Seq arg must have length')
while count:
yield seq[int(self.random() * seqlen)]
count -= 1 |
Note: these values reflect the state of the issue at the time it was migrated and might not reflect the current state.
Show more details
GitHub fields:
bugs.python.org fields:
The text was updated successfully, but these errors were encountered: