From bae79d35bfc643f5a2721abd78eec01a834c8f30 Mon Sep 17 00:00:00 2001 From: Raymond Hettinger Date: Wed, 7 Apr 2021 15:57:06 -0700 Subject: [PATCH] Improve the error message for choices(population, 10) --- Lib/random.py | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/Lib/random.py b/Lib/random.py index 0df26645d9e19e..3a835aef0bc1d4 100644 --- a/Lib/random.py +++ b/Lib/random.py @@ -518,7 +518,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: