Enum and random.choice

random.choice and Enum interact poorly, because indexing an enum class doesn't work as choice expects:
Of course one can do `random.choice(list(C.__members__.values()))` but this feels a bit awkward. The source for random.choice is def choice(self, seq): """Choose a random element from a non-empty sequence.""" try: i = self._randbelow(len(seq)) except ValueError: raise IndexError('Cannot choose from an empty sequence') return seq[i] Adding seq = list(seq) should be enough to fix this. Antony

On 21 Oct 2013 15:52, "Antony Lee" <antony.lee@berkeley.edu> wrote:
random.choice and Enum interact poorly, because indexing an enum class
doesn't work as choice expects:
this feels a bit awkward.
How is this different from passing a dict to random.choice? Enum classes are iterables, not sequences. Cheers, Nick.

On 10/21/2013 3:50 PM, Antony Lee wrote:
Comparing with dicts is a good argument against my suggested change, I missed that point.
Also AFAIK list(seq) would do a full copy of the list every time you called choice(), which could murder performance with big lists and tight loops. Matt

On 21 Oct 2013 15:52, "Antony Lee" <antony.lee@berkeley.edu> wrote:
random.choice and Enum interact poorly, because indexing an enum class
doesn't work as choice expects:
this feels a bit awkward.
How is this different from passing a dict to random.choice? Enum classes are iterables, not sequences. Cheers, Nick.

On 10/21/2013 3:50 PM, Antony Lee wrote:
Comparing with dicts is a good argument against my suggested change, I missed that point.
Also AFAIK list(seq) would do a full copy of the list every time you called choice(), which could murder performance with big lists and tight loops. Matt
participants (3)
-
Antony Lee
-
Matt Chaput
-
Nick Coghlan