Skip to content
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

Closed
hoffman mannequin opened this issue Jun 1, 2004 · 7 comments
Closed

random.choice([]) should return more intelligible exception #40318

hoffman mannequin opened this issue Jun 1, 2004 · 7 comments
Labels
stdlib Python modules in the Lib dir

Comments

@hoffman
Copy link
Mannequin

hoffman mannequin commented Jun 1, 2004

BPO 964230
Nosy @rhettinger, @terryjreedy

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:

assignee = None
closed_at = <Date 2004-06-05.15:51:45.000>
created_at = <Date 2004-06-01.12:39:19.000>
labels = ['library']
title = 'random.choice([]) should return more intelligible exception'
updated_at = <Date 2004-06-05.15:51:45.000>
user = 'https://bugs.python.org/hoffman'

bugs.python.org fields:

activity = <Date 2004-06-05.15:51:45.000>
actor = 'terry.reedy'
assignee = 'none'
closed = True
closed_date = None
closer = None
components = ['Library (Lib)']
creation = <Date 2004-06-01.12:39:19.000>
creator = 'hoffman'
dependencies = []
files = []
hgrepos = []
issue_num = 964230
keywords = []
message_count = 7.0
messages = ['20945', '20946', '20947', '20948', '20949', '20950', '20951']
nosy_count = 3.0
nosy_names = ['rhettinger', 'terry.reedy', 'hoffman']
pr_nums = []
priority = 'low'
resolution = None
stage = None
status = 'closed'
superseder = None
type = None
url = 'https://bugs.python.org/issue964230'
versions = ['Python 2.4']

@hoffman
Copy link
Mannequin Author

hoffman mannequin commented Jun 1, 2004

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
at the bottom of a traceback.

I suggest something like ValueError: sequence must not
be empty.

@hoffman hoffman mannequin closed this as completed Jun 1, 2004
@hoffman hoffman mannequin added the stdlib Python modules in the Lib dir label Jun 1, 2004
@rhettinger
Copy link
Contributor

Logged In: YES
user_id=80475

-0

While a ValueError would be appropriate, the status quo
doesn't bug me much and changing it could break code if
someone is currently trapping the IndexError.

@hoffman
Copy link
Mannequin Author

hoffman mannequin commented Jun 5, 2004

Logged In: YES
user_id=987664

I thought of that after I submitted. :-)

Might it be better to raise an IndexError with a message
similar to "sequence must not be empty" instead? It would
just make debugging that much easier.

@rhettinger
Copy link
Contributor

Logged In: YES
user_id=80475

That's better, but I'm still -0. This function is apt to
be called inside a loop, so it would be a bummer to slow
down everyone's code just to rewrite the error message.

For better or worse, it is the nature of Python tracebacks
to raise RoadWeavingErrors when a DontDrinkAndDriveWarning
would be more to the point.

I recommend closing this, but if you really think it's an
essential life saver, then assign to Tim and see if you can
persuade him.

@hoffman
Copy link
Mannequin Author

hoffman mannequin commented Jun 5, 2004

Logged In: YES
user_id=987664

You have a point. What about rewriting the line to read:
return seq[int(self.random() * len(seq))] # raises IndexError if
seq is empty

The comment would be a good hint.

@rhettinger
Copy link
Contributor

Logged In: YES
user_id=80475

Okay. Fixed. See Lib/random.py 1.61.

@terryjreedy
Copy link
Member

Logged In: YES
user_id=593130

More succinctly:
# empty seq raises IndexError
Commenting source code for traceback clarity has been
suggested before as a way to enhance without breaking.
Works for me

For making repeated choices, however, a generator would be
faster for n much larger than 0. Something like

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

@ezio-melotti ezio-melotti transferred this issue from another repository Apr 9, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
stdlib Python modules in the Lib dir
Projects
None yet
Development

No branches or pull requests

2 participants