random.choice on Enum

Question:

I would like to use random.choice on an Enum.

I tried:

class Foo(Enum):
    a = 0
    b = 1
    c = 2
bar = random.choice(Foo)

But this code fails with a KeyError. How can I choose a random member of Enum?

Asked By: Co_42

||

Answers:

An Enum is not a sequence, so you cannot pass it to random.choice(), which tries to pick an index between 0 and len(Foo). Like a dictionary, index access to an Enum instead expects enumeration names to be passed in, so Foo[<integer>] fails here with a KeyError.

You can cast it to a list first:

bar = random.choice(list(Foo))

This works because Enum does support iteration.

Demo:

>>> from enum import Enum
>>> import random
>>> class Foo(Enum):
...     a = 0
...     b = 1
...     c = 2
... 
>>> random.choice(list(Foo))
<Foo.a: 0>
Answered By: Martijn Pieters
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.