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 type
1from functools import singledispatch
2
# The decorated function becomes the fallback for unregistered types
3@singledispatch
4def process(arg):
# Used for any type without its own handler
5 return f"Unknown: {arg}"
6
# Register a handler for int; the name _ is never called directly
7@process.register(int)
8def _(arg):
# Integers are doubled
9 return f"Integer: {arg * 2}"
10
# Register a handler for str
11@process.register(str)
12def _(arg):
# Strings are converted to uppercase
13 return f"String: {arg.upper()}"
14
# 5 goes to the int handler, "hi" to the str one: Integer: 10 String: HI
15print(process(5), process("hi"))

Output

Integer: 10 String: HI
Practice typing this code

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

More Python examples at level 4

← Python typing practice