[Python-ideas] Enum and random.choice

Antony Lee antony.lee at berkeley.edu
Mon Oct 21 21:50:58 CEST 2013


Comparing with dicts is a good argument against my suggested change, I
missed that point.
Antony


2013/10/21 Nick Coghlan <ncoghlan at gmail.com>

>
> 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/d513fcd9/attachment.html>


More information about the Python-ideas mailing list