Skip to Content
Course content

182: The functools Module: singledispatch

Click on the "Edit" button in the top corner of the screen to edit your slide content.

Why not just use if isinstance() everywhere?

I've seen this a lot in codebase reviews: a single function that's 100 lines long, mostly consisting of a giant if-elif-else chain checking the type of the first argument. It's a nightmare to maintain. Every time you add a new supported data type, you have to go back into that original function, risk breaking existing logic, and make the function even longer.

singledispatch is Python's way of letting you implement "function overloading." Instead of one massive function that knows how to handle everything, you create one "generic" function and then register specialized versions of it for specific types. It keeps your code decoupled. You aren't writing one function that knows about ten types; you're writing ten small functions that each know about one type.

How do I actually implement a singledispatch function?

You'll want to import singledispatch from the functools module. First, you define your base function and decorate it. This base function acts as the "fallback"β€”it's what gets called if the input doesn't match any of your specialized types.

Let's say we're building a system that formats data for a report. Depending on whether we get a string, a list, or an integer, we want a different output format:

from functools import singledispatch

@singledispatch
def format_data(data):
    # This is the fallback for any type we haven't explicitly handled
    return f"Unsupported type: {type(data).__name__} -> {data}"

@format_data.register
def _(data: int):
    return f"Numeric Value: {data:,}"

@format_data.register
def _(data: list):
    return f"Collection: {', '.join(map(str, data))}"

@format_data.register
def _(data: str):
    return f"Text: {data.strip().capitalize()}"

# Let's try it out
print(format_data(1234567))     # Numeric Value: 1,234,567
print(format_data(["A", "B"]))  # Collection: A, B
print(format_data(" hello "))   # Text: Hello
print(format_data(3.14))        # Unsupported type: float -> 3.14

Notice how I used _ as the function name for the registered versions? Since the @format_data.register decorator handles the mapping, the actual name of the helper function doesn't matter. Using an underscore is a common convention to signal that these are internal implementation details.

Can I extend this later without touching the original code?

This is actually the "killer feature" of singledispatch. In a real-world project, you might have a library that provides the format_data function, but you need it to handle a custom class defined in your application code.

Normally, you'd be stuck. You can't edit the library's source code. But with singledispatch, you can register a new type from anywhere in your project. I love this because it follows the Open-Closed Principle: the code is open for extension but closed for modification.

class UserProfile:
    def __init__(self, name, email):
        self.name = name
        self.email = email

# We are adding this functionality WITHOUT touching the original format_data definition
@format_data.register
def _(data: UserProfile):
    return f"User: {data.name} <{data.email}>"

user = UserProfile("Jane Doe", "jane@example.com")
print(format_data(user))  # User: Jane Doe <jane@example.com>

I should mention one limitation: singledispatch only looks at the type of the first argument. If you need to dispatch based on multiple arguments or different positions, you'd need something more complex, but for 90% of "type-based logic" cases, this is exactly what you need.




πŸ“‹ Practical Task

Exercise: Building a Multi-Type Document Parser

You are building a tool that processes different types of input data into a standardized string format for a logging system. Your goal is to replace a messy if/else block with singledispatch.

Requirements:

  • Create a generic function parse_content using @singledispatch.
  • The base function should return: "Unknown format: [value]".
  • Register a handler for str that returns the string in all uppercase.
  • Register a handler for dict that returns a string of the keys joined by pipes (e.g., "key1|key2|key3").
  • Register a handler for tuple that returns only the first element of the tuple.
  • Test your implementation with a string, a dictionary, a tuple, and an unsupported type (like a float) to ensure the fallback works.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.