Skip to content

Commit fa03efd

Browse files
Improve the error message for choices(population, 10) (GH-25267) (GH-25477)
1 parent 072ec69 commit fa03efd

File tree

1 file changed

+9
-1
lines changed

1 file changed

+9
-1
lines changed

Lib/random.py

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -485,7 +485,15 @@ def choices(self, population, weights=None, *, cum_weights=None, k=1):
485485
floor = _floor
486486
n += 0.0 # convert to float for a small speed improvement
487487
return [population[floor(random() * n)] for i in _repeat(None, k)]
488-
cum_weights = list(_accumulate(weights))
488+
try:
489+
cum_weights = list(_accumulate(weights))
490+
except TypeError:
491+
if not isinstance(weights, int):
492+
raise
493+
k = weights
494+
raise TypeError(
495+
f'The number of choices must be a keyword argument: {k=}'
496+
) from None
489497
elif weights is not None:
490498
raise TypeError('Cannot specify both weights and cumulative weights')
491499
if len(cum_weights) != n:

0 commit comments

Comments
 (0)