[Python-ideas] Enum and random.choice

Nick Coghlan ncoghlan at gmail.com
Mon Oct 21 13:45:44 CEST 2013


On 21 Oct 2013 15:52, "Antony Lee" <antony.lee at 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 at python.org
> https://mail.python.org/mailman/listinfo/python-ideas
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20131021/37ec19b5/attachment.html>


More information about the Python-ideas mailing list