Skip to main content
🔒 Preview mode. The first 15 Foundations lessons are free; this one is Pro. Start a 7-day trial to unlock the editor, AI hints and the rest of the curriculum. Card required, cancel any time in Dashboard.Start 7-day trial →
← CoursesSenior Deep-DivesModule 7 · Memory, GC, modern typingfunctools.singledispatch — type-dispatched generic functionspredict121 / 161
+150 XP
Task
📝 **Task:** Predict the exact output. The function `describe` dispatches on the type of its first arg. Watch the last call carefully — `True` is a `bool`, which inherits from `int`. There's no `bool` handler registered, so the MRO walk routes the call to the `int` handler. 📋 Implement the function above. Tests run automatically. 💡 **Hint:** Re-read the theory if you get stuck.
Predict the output

Read the code carefully

from functools import singledispatch


@singledispatch
def describe(value: object) -> str:
    return f"unknown: {value!r}"


@describe.register
def _(value: int) -> str:
    return f"int: {value}"


@describe.register
def _(value: list) -> str:
    return f"list of {len(value)}"


@describe.register
def _(value: dict) -> str:
    return f"dict with keys {sorted(value)}"


print(describe(42))
print(describe([1, 2, 3]))
print(describe({"b": 2, "a": 1}))
print(describe(3.14))
print(describe(True))

What will the program print? Write here:

💬 Discussion

Be the first to ask a question or share a tip.
Sign in to join the discussion. Reading is free.
Loading discussion…