Skip to content

[3.9] Improve the error message for choices(population, 10) (GH-25267) #25477

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

Merged
merged 1 commit into from
Apr 20, 2021
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 9 additions & 1 deletion Lib/random.py
Original file line number Diff line number Diff line change
Expand Up @@ -485,7 +485,15 @@ def choices(self, population, weights=None, *, cum_weights=None, k=1):
floor = _floor
n += 0.0 # convert to float for a small speed improvement
return [population[floor(random() * n)] for i in _repeat(None, k)]
cum_weights = list(_accumulate(weights))
try:
cum_weights = list(_accumulate(weights))
except TypeError:
if not isinstance(weights, int):
raise
k = weights
raise TypeError(
f'The number of choices must be a keyword argument: {k=}'
) from None
elif weights is not None:
raise TypeError('Cannot specify both weights and cumulative weights')
if len(cum_weights) != n:
Expand Down