Enum and random.choice
random.choice and Enum interact poorly, because indexing an enum class doesn't work as choice expects:
import enum, random class C(enum.Enum): a, b = 1, 2 ... random.choice(C) <traceback...> KeyError: 1
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:
import enum, random class C(enum.Enum): a, b = 1, 2 ... random.choice(C) <traceback...> KeyError: 1
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.
How is this different from passing a dict to random.choice? Enum classes are iterables, not sequences. Cheers, Nick.
Antony
_______________________________________________ Python-ideas mailing list Python-ideas@python.org https://mail.python.org/mailman/listinfo/python-ideas
Comparing with dicts is a good argument against my suggested change, I missed that point. Antony 2013/10/21 Nick Coghlan <ncoghlan@gmail.com>
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:
import enum, random class C(enum.Enum): a, b = 1, 2 ... random.choice(C) <traceback...> KeyError: 1
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.
How is this different from passing a dict to random.choice? Enum classes are iterables, not sequences.
Cheers, Nick.
Antony
_______________________________________________ Python-ideas mailing list Python-ideas@python.org https://mail.python.org/mailman/listinfo/python-ideas
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