Skip to content

Commit 2a36b09

Browse files
authored
Improve the error message for choices(population, 10) (GH-25267)
1 parent 503cdc7 commit 2a36b09

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
@@ -518,7 +518,15 @@ def choices(self, population, weights=None, *, cum_weights=None, k=1):
518518
floor = _floor
519519
n += 0.0 # convert to float for a small speed improvement
520520
return [population[floor(random() * n)] for i in _repeat(None, k)]
521-
cum_weights = list(_accumulate(weights))
521+
try:
522+
cum_weights = list(_accumulate(weights))
523+
except TypeError:
524+
if not isinstance(weights, int):
525+
raise
526+
k = weights
527+
raise TypeError(
528+
f'The number of choices must be a keyword argument: {k=}'
529+
) from None
522530
elif weights is not None:
523531
raise TypeError('Cannot specify both weights and cumulative weights')
524532
if len(cum_weights) != n:

0 commit comments

Comments
 (0)