Intermediate LevelPython
How does @functools.singledispatch enable Function Overloading based on the type of the first argument?
❓ Interview Prompt: Explain Function Overloading, `@functools.singledispatch`, type-based dispatch, and registering type-specific implementations.
Python does not support traditional static method overloading. '@functools.singledispatch' enables Single-Dispatch Generic Functions:
How It Works:
Decorates a base function, allowing you to register specialized implementation variants ('@func.register(int)') dispatched dynamically based on the type of the first argument!
Code Implementation Example
python
from functools import singledispatch
@singledispatch
def format_data(arg):
return f'Generic: {arg}'
@format_data.register(int)
def _(arg: int):
return f'Integer: {arg:,}'
@format_data.register(list)
def _(arg: list):
return f'List of {len(arg)} items'
print(format_data(1000000)) # Integer: 1,000,000
print(format_data([1, 2])) # List of 2 items💡Overloading functions based on parameter types using @singledispatch.
🎯 Interview Key Takeaway
Use @functools.singledispatch to implement clean, type-based function overloading in Python.
#singledispatch#Polymorphism#Overloading#Intermediate
Back to all Python Questions→