singledispatch in Python
Level 4263 keystrokes
This uses @singledispatch to create a function that dispatches based on argument type.
Python code
# singledispatch picks an implementation by the first argument's type1from functools import singledispatch2 # The decorated function becomes the fallback for unregistered types3@singledispatch4def process(arg): # Used for any type without its own handler5 return f"Unknown: {arg}"6 # Register a handler for int; the name _ is never called directly7@process.register(int)8def _(arg): # Integers are doubled9 return f"Integer: {arg * 2}"10 # Register a handler for str11@process.register(str)12def _(arg): # Strings are converted to uppercase13 return f"String: {arg.upper()}"14 # 5 goes to the int handler, "hi" to the str one: Integer: 10 String: HI15print(process(5), process("hi"))Output
Integer: 10 String: HI
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.
(× 9)× 9"× 8:× 6.× 3{× 3}× 3@× 3_× 2,× 1