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 11 · Decorator patterns at scalefunctools.singledispatchmethod — type dispatch when there's a self in the waypredict153 / 161
+150 XP
Task
📝 **Task:** Predict the 5-line output. A `Formatter` class has a `format` method dispatched by the SECOND argument's type (singledispatchmethod handles the self-skip). Test inputs cover int / list / dict / unmatched float (falls to default) / bool (which inherits from int → routes to int handler, the same gotcha as sr-116). 📋 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 singledispatchmethod


class Formatter:
    @singledispatchmethod
    def format(self, value: object) -> str:
        return f"unknown: {value!r}"

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

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

    @format.register
    def _(self, value: dict) -> str:
        return f"dict with {len(value)} keys"


f = Formatter()
print(f.format(42))
print(f.format([1, 2, 3]))
print(f.format({"a": 1, "b": 2}))
print(f.format(3.14))
print(f.format(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…