Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

random.choice on Enum

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?

like image 429
Co_42 Avatar asked Jun 16 '14 12:06

Co_42


People also ask

How do you randomize enums in Systemverilog?

Show activity on this post. typedef enum int { IPV4_VERSION = 0, IPV4_IHL = 1, IPV4_TOTAL_LENGTH = 2,IPV4_CHECKSUM = 3 } ipv4_corrupton; ipv4_corrupton ipv4_corrupt; std::randomize(ipv4_corrupt) with {ipv4_corrupt dist { IPV4_VERSION :=2,IPV4_IHL := 4,IPV4_TOTAL_LENGTH := 4,IPV4_CHECKSUM := 2}; };

What is an enum Java?

An enum type is a special data type that enables for a variable to be a set of predefined constants. The variable must be equal to one of the values that have been predefined for it. Common examples include compass directions (values of NORTH, SOUTH, EAST, and WEST) and the days of the week.


1 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>
like image 195
Martijn Pieters Avatar answered Oct 13 '22 20:10

Martijn Pieters