typestar

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

  1. auto() assigns each member a distinct value.
  2. Members compare by identity and live in sets.
  3. .name, .value, and iteration expose them.

Keywords and builtins used here

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.

Type this snippet

Step 3 of 4 in Typing & dataclasses, step 22 of 53 in Pythonic Python.

← Previous Next →