This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

classification
Title: Harmonize random.choice(s) behavior with random.sample on iterators
Type: enhancement Stage: resolved
Components: Library (Lib) Versions: Python 3.8
process
Status: closed Resolution: rejected
Dependencies: Superseder:
Assigned To: rhettinger Nosy List: Lex Flagel, python-dev, rhettinger, xtreak
Priority: normal Keywords:

Created on 2019-07-29 19:28 by Lex Flagel, last changed 2022-04-11 14:59 by admin. This issue is now closed.

Pull Requests
URL Status Linked Edit
PR 18694 closed python-dev, 2020-02-28 21:07
Messages (3)
msg348680 - (view) Author: Lex Flagel (Lex Flagel) Date: 2019-07-29 19:28
It would be nice to make random.sample and random.choice both have the same behavior with iterators. Currently random.sample accepts them happily, and whereas random.choice does not.  E.g.

> import random
> d = {'a':1, 'b':2}
> random.sample(d.keys(),1)
Out: ['a']

> random.choice(d.keys())
Out: TypeError: 'dict_keys' object is not subscriptable

random.choice could be redefined as follows to harmonize behavior, but I think the solution for random.choices maybe be more involved:

def choice(x): 
    random.sample(x,1)[0]
msg348682 - (view) Author: Karthikeyan Singaravelan (xtreak) * (Python committer) Date: 2019-07-29 19:32
Seems similar to https://bugs.python.org/issue37682
msg348828 - (view) Author: Raymond Hettinger (rhettinger) * (Python committer) Date: 2019-07-31 23:59
The sample() function accepts d.keys() because a keys view is registered as being an instance of collections.abc.Set.  We have to do that because sample() is specifically documented as accepting sets.  If we had it do over again, that functionality would likely not be supported (it implicitly the population into a tuple).

For a fine-grained function like choice() that implicit population conversion would make no sense at all.  For choices(), we can choose not to make that API mistake again.

Thanks for the suggestion, but I am going to decline.  It isn't something that we need in practice and it would add complication for near zero gain.  (Also, there is no rule that all of these functions have to accept the same kinds of inputs -- different algorithms and different use cases allow for some flexibility).
History
Date User Action Args
2022-04-11 14:59:18adminsetgithub: 81889
2020-02-28 21:07:40python-devsetnosy: + python-dev

pull_requests: + pull_request18055
2019-07-31 23:59:17rhettingersetstatus: open -> closed
resolution: rejected
messages: + msg348828

stage: resolved
2019-07-31 23:40:56rhettingersetassignee: rhettinger
2019-07-29 19:32:33xtreaksetnosy: + rhettinger, xtreak
messages: + msg348682
2019-07-29 19:28:24Lex Flagelcreate