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

rhettinger webhook-mailer at python.org
Tue Apr 20 02:15:58 EDT 2021


https://github.com/python/cpython/commit/fa03efda3dc6ad118788bebc61079cd481c0b24c
commit: fa03efda3dc6ad118788bebc61079cd481c0b24c
branch: 3.9
author: Miss Islington (bot) <31488909+miss-islington at users.noreply.github.com>
committer: rhettinger <rhettinger at users.noreply.github.com>
date: 2021-04-19T23:15:50-07:00
summary:

Improve the error message for choices(population, 10) (GH-25267) (GH-25477)

files:
M Lib/random.py

diff --git a/Lib/random.py b/Lib/random.py
index 36e16a9063b53..53252764a5b5d 100644
--- a/Lib/random.py
+++ b/Lib/random.py
@@ -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:



More information about the Python-checkins mailing list