[Python-ideas] Enum and random.choice

Antony Lee antony.lee at berkeley.edu
Mon Oct 21 07:51:40 CEST 2013


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
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20131020/0b9c7efd/attachment.html>


More information about the Python-ideas mailing list