Enums in Python
Naming a fixed set of related constants with Enum.
from enum import Enum, auto
class Suit(Enum):
CLUBS = auto()
DIAMONDS = auto()
HEARTS = auto()
SPADES = auto()
red = {Suit.DIAMONDS, Suit.HEARTS}
pick = Suit.SPADES
is_red = pick in red
name = pick.name
number = pick.value
every = list(Suit)
How it works
auto()assigns each member a distinct value.- Members compare by identity and live in sets.
.name,.value, and iteration expose them.
Keywords and builtins used here
Suitclasslist
The run, in numbers
- Lines
- 16
- Characters to type
- 245
- Tokens
- 69
- Three-star pace
- 100 tpm
At the three-star pace of 100 tokens a minute, this run takes about 41 seconds.
Step 3 of 4 in Typing & dataclasses, step 22 of 53 in Pythonic Python.