Enum with auto() in Python

Level 4148 keystrokes

This creates an enum with auto-generated values and iterates over it.

Python code

# Import the Enum base class and the auto helper
1from enum import Enum, auto
2
# Inheriting from Enum turns the class attributes into members
3class Color(Enum):
# auto() numbers the members from 1: RED=1, GREEN=2, BLUE=3
4 RED = auto()
5 GREEN = auto()
6 BLUE = auto()
7
# Iterating over the class yields the members in definition order
8for color in Color:
# name is the member's name, value its number: RED: 1 …
9 print(f"{color.name}: {color.value}")

Output

RED: 1
GREEN: 2
BLUE: 3
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this Python code and how often they appear.

  • (× 5
  • )× 5
  • :× 3
  • =× 3
  • .× 2
  • "× 2
  • {× 2
  • }× 2
  • ,× 1

More Python examples at level 4

← Python typing practice