Enumerations · Practice
Quiz & exercises
Answer each question to see the explanation. Your best score is saved in this browser.
Quiz
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 ✓ Passed
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.
def lookup(enum_cls, key):
# your code here
return enum_cls(key)
from enum import Enum
class Status(Enum):
PENDING = 'pending'
RUNNING = 'running'
BUSY = 'running' # alias of RUNNING
class Code(Enum):
OK = 0
ERROR = 1
def test_member():
"""a member is returned unchanged"""
assert lookup(Status, Status.PENDING) is Status.PENDING
def test_name():
"""a name string finds the member"""
assert lookup(Status, 'PENDING') is Status.PENDING, f"got {lookup(Status, 'PENDING')!r}"
def test_alias_name():
"""an alias name finds the canonical member"""
assert lookup(Status, 'BUSY') is Status.RUNNING
def test_value():
"""a value finds the member"""
assert lookup(Status, 'running') is Status.RUNNING
assert lookup(Code, 1) is Code.ERROR
def test_missing():
"""an unknown key raises ValueError"""
try:
lookup(Status, 'done')
except ValueError:
pass
else:
assert False, "expected ValueError for 'done'"
def test_other_enum_member():
"""a member of another enumeration raises ValueError"""
try:
result = lookup(Code, Status.PENDING)
except ValueError:
pass
else:
assert False, f"expected ValueError, got {result!r}"
Hints (3)
isinstance(key, enum_cls)tells you whetherkeyis already one of its members.enum_cls.__members__maps every name (aliases too) to its member.enum_cls(key)looks up by value and raisesValueErrorwhen nothing matches.- 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 NoneExercise 2: Map aliases to canonical names ✓ Passed
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'}.
def alias_map(enum_cls):
# your code here
return {member.name: member.name for member in enum_cls}
from enum import Enum
class NumSides(Enum):
Triangle = 3
Rectangle = 4
Square = 4
Rhombus = 4
class Status(Enum):
ready = 1
running = 2
busy = 2
ok = 3
ran_ok = 3
class Plain(Enum):
A = 1
B = 2
def test_numsides():
"""aliases of one member"""
result = alias_map(NumSides)
assert result == {'Square': 'Rectangle', 'Rhombus': 'Rectangle'}, f"got {result}"
def test_status():
"""aliases of several members"""
result = alias_map(Status)
assert result == {'busy': 'running', 'ran_ok': 'ok'}, f"got {result}"
def test_no_aliases():
"""no aliases gives an empty dict"""
assert alias_map(Plain) == {}, f"got {alias_map(Plain)}"
Hints (2)
- Iterating the enumeration skips aliases. Which attribute lists every name?
- An alias is a name in
__members__whose member has a differentname.
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 ✓ Passed
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.)
from enum import Enum
from functools import total_ordering
class DeclOrderEnum(Enum):
def __lt__(self, other):
return self.value < other.value
class Size(DeclOrderEnum):
SMALL = 's'
MEDIUM = 'm'
LARGE = 'l'
def test_less_than():
"""SMALL < MEDIUM < LARGE"""
assert Size.SMALL < Size.MEDIUM < Size.LARGE
def test_other_operators():
"""<=, > and >= work"""
assert Size.SMALL <= Size.SMALL
assert Size.LARGE > Size.SMALL
assert Size.MEDIUM >= Size.SMALL
assert not (Size.LARGE <= Size.MEDIUM)
def test_sorting():
"""sorted() and max() follow declaration order"""
assert sorted([Size.LARGE, Size.SMALL, Size.MEDIUM]) == [Size.SMALL, Size.MEDIUM, Size.LARGE]
assert max(Size) is Size.LARGE
def test_reusable():
"""the base class works for other enumerations too"""
class Phase(DeclOrderEnum):
READY = 30
RUNNING = 20
DONE = 10
assert Phase.READY < Phase.RUNNING < Phase.DONE
def test_foreign_type():
"""comparing with a non-member raises TypeError"""
try:
Size.SMALL < 's'
except TypeError:
pass
else:
assert False, "expected TypeError"
def test_other_enum():
"""comparing members of different enumerations raises TypeError"""
class Other(DeclOrderEnum):
A = 1
try:
Size.SMALL < Other.A
except TypeError:
pass
else:
assert False, "expected TypeError"
Hints (3)
list(self.__class__)gives the members in declaration order, and.index()gives a position you can compare.- Return
NotImplementedwhenotherisn't a member of the same enumeration; Python then raises theTypeErrorfor you. @functools.total_orderingfills 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 ✓ Passed
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().
import enum
class KebabEnum(enum.Enum):
pass
class Endpoint(KebabEnum):
HOME = enum.auto()
USER_PROFILE = enum.auto()
ORDER_HISTORY = enum.auto()
import enum
def test_values():
"""values are kebab-case names"""
assert [m.value for m in Endpoint] == ['home', 'user-profile', 'order-history'], \
f"got {[m.value for m in Endpoint]}"
def test_str():
"""str() gives the value"""
assert str(Endpoint.USER_PROFILE) == 'user-profile', f"got {str(Endpoint.USER_PROFILE)!r}"
assert f'/{Endpoint.HOME}' == '/home'
def test_lookup():
"""members can be looked up by their kebab value"""
assert Endpoint('order-history') is Endpoint.ORDER_HISTORY
def test_reusable():
"""the base works for another enumeration"""
class Event(KebabEnum):
PAGE_VIEW = enum.auto()
ADD_TO_CART = enum.auto()
assert Event.ADD_TO_CART.value == 'add-to-cart'
assert len(Event) == 2
Hints (3)
- Define
_generate_next_value_(name, start, count, last_values)as a plain function in the base class. It receives the member'sname. - Because it lives in the base class, it is automatically defined before the subclass's members.
- Override
__str__to returnself.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()