Enumerations · Practice

Quiz & exercises

Answer each question to see the explanation. Your best score is saved in this browser.

Quiz

1. What does this print?
from enum import Enum

class Status(Enum):
    PENDING = 'pending'
    DONE = 'done'

print(Status.PENDING == 'pending', Status('done') is Status.DONE)
2. You receive the string 'PENDING' (a member name) from a JSON payload. Which expression returns the matching member of Status?
3. What does this print on Python 3.13?
from enum import Enum

class Status(Enum):
    PENDING = 'pending'

print('PENDING' in Status, 'pending' in Status, 'PENDING' in Status.__members__)
4. What does this print?
from enum import Enum

class Shape(Enum):
    RECTANGLE = 4
    SQUARE = 4
    TRIANGLE = 3

print(len(Shape), Shape.SQUARE.name, len(Shape.__members__))
5. What happens when this class is defined?
import enum

@enum.unique
class Job(enum.Enum):
    READY = 1
    WAITING = 1
    DONE = 2
6. Why does this raise a TypeError?
from enum import Enum

class Color(Enum):
    RED = 1

class MoreColors(Color):
    GREEN = 2
7. What does this print?
from enum import Enum

class State(Enum):
    READY = 1
    BUSY = 0

print(bool(State.BUSY))
8. An enumeration defines __eq__ but not __hash__. What is the consequence?
9. What does this print?
from enum import Enum

class AppStatus(Enum):
    OK = (0, 'Fine')
    FAILED = (1, 'Broken')

    def __new__(cls, code, phrase):
        member = object.__new__(cls)
        member._value_ = code
        member.phrase = phrase
        return member

print(AppStatus(1).name, AppStatus.OK.value, AppStatus.OK.phrase)
10. What does this print on Python 3.13?
from enum import IntEnum

class Priority(IntEnum):
    LOW = 1
    HIGH = 2

print(str(Priority.HIGH), Priority.HIGH + 1, Priority.LOW < Priority.HIGH)
11. What does this print?
import enum

class State(enum.Enum):
    WAITING = enum.auto()
    STARTED = 1
    FINISHED = enum.auto()

print(list(State))
12. What does this print?
import enum

class Perm(enum.Flag):
    R = enum.auto()
    W = enum.auto()
    X = enum.auto()

rx = Perm.R | Perm.X
print(rx.value, Perm.W in rx, len(rx))

Coding exercises

Write your code, then press Check (or Shift+Enter) to run the tests. Drafts are saved as you type.

Exercise 1: Look up a member any way you like

Write lookup(enum_cls, key) that returns the member of enum_cls described by key, which may be:

1. a member of enum_cls itself (return it unchanged), 2. a member name as a string (aliases included), or 3. a member value.

Try them in that order. If nothing matches, raise a ValueError. A member of a different enumeration must not be accepted.

Hints (3)
  1. isinstance(key, enum_cls) tells you whether key is already one of its members.
  2. enum_cls.__members__ maps every name (aliases too) to its member. enum_cls(key) looks up by value and raises ValueError when nothing matches.
  3. Calling an enumeration with a member of a different enumeration also raises ValueError, so the value lookup handles that case for you.
Show a solution
def lookup(enum_cls, key):
    if isinstance(key, enum_cls):
        return key
    if isinstance(key, str) and key in enum_cls.__members__:
        return enum_cls.__members__[key]
    try:
        return enum_cls(key)
    except ValueError:
        raise ValueError(f'{key!r} does not match any member of {enum_cls.__name__}') from None

Exercise 2: Map aliases to canonical names

Write alias_map(enum_cls) that returns a dictionary mapping each alias name of the enumeration to the name of the canonical member it refers to. Canonical members themselves must not appear as keys.

For example, for Rectangle = 4; Square = 4; Rhombus = 4 the result is {'Square': 'Rectangle', 'Rhombus': 'Rectangle'}.

Hints (2)
  1. Iterating the enumeration skips aliases. Which attribute lists every name?
  2. An alias is a name in __members__ whose member has a different name.
Show a solution
def alias_map(enum_cls):
    return {
        name: member.name
        for name, member in enum_cls.__members__.items()
        if name != member.name
    }

Exercise 3: Ordered by declaration, not by value

Create a member-less base enumeration DeclOrderEnum whose members compare by the order in which they were declared, ignoring their values. All of <, <=, > and >= must work between members of the same enumeration, and comparing with anything else must raise TypeError.

Then define Size(DeclOrderEnum) with members SMALL = 's', MEDIUM = 'm' and LARGE = 'l'. (Notice that alphabetically 'l' < 'm' < 's', so comparing values would give the wrong answer.)

Hints (3)
  1. list(self.__class__) gives the members in declaration order, and .index() gives a position you can compare.
  2. Return NotImplemented when other isn't a member of the same enumeration; Python then raises the TypeError for you.
  3. @functools.total_ordering fills in <=, > and >= from __lt__.
Show a solution
from enum import Enum
from functools import total_ordering

@total_ordering
class DeclOrderEnum(Enum):
    def __lt__(self, other):
        if isinstance(other, self.__class__):
            members = list(self.__class__)
            return members.index(self) < members.index(other)
        return NotImplemented

class Size(DeclOrderEnum):
    SMALL = 's'
    MEDIUM = 'm'
    LARGE = 'l'

Exercise 4: Automatic kebab-case values

Create a member-less base enumeration KebabEnum whose auto() values are the member name in lower case with underscores replaced by hyphens (USER_PROFILE becomes 'user-profile'). Its members should also convert to that string with str().

Then define Endpoint(KebabEnum) with members HOME, USER_PROFILE and ORDER_HISTORY, all using auto().

Hints (3)
  1. Define _generate_next_value_(name, start, count, last_values) as a plain function in the base class. It receives the member's name.
  2. Because it lives in the base class, it is automatically defined before the subclass's members.
  3. Override __str__ to return self.value; f-strings follow __str__ too.
Show a solution
import enum

class KebabEnum(enum.Enum):
    def _generate_next_value_(name, start, count, last_values):
        return name.lower().replace('_', '-')

    def __str__(self):
        return self.value

class Endpoint(KebabEnum):
    HOME = enum.auto()
    USER_PROFILE = enum.auto()
    ORDER_HISTORY = enum.auto()