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
?
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}; };
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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With