SyntaxStudy
Sign Up
Python Advanced 4 min read

@singledispatch

@singledispatch

functools.singledispatch implements function overloading based on the type of the first argument.

Example
from functools import singledispatch

@singledispatch
def process(arg):
    print(f"Generic: {arg}")

@process.register(int)
def _(arg):
    print(f"Integer: {arg * 2}")

@process.register(str)
def _(arg):
    print(f"String: {arg.upper()}")

process(5)      # Integer: 10
process("hi")   # String: HI
Pro Tip

singledispatch only dispatches on the first argument type.