Signature-based Function Overloading in Python

Lie Ryan lie.1296 at
Tue Feb 23 23:55:21 CET 2010

On 02/24/10 05:25, Michael Rudolf wrote:
> Just a quick question about what would be the most pythonic approach in
> this.
> In Java, Method Overloading is my best friend, but this won't work in
> Python:
> So - What would be the most pythonic way to emulate this?
> Is there any better Idom than:
>>>> def a(x=None):
>     if x is None:
>         pass
>     else:
>         pass

Python's idiom for this has always been to use "if arg is None:"; but
now with the (relatively) new decorator feature, though is not yet a
popular idiom, it is now possible to do something like this:

#!/usr/bin/env python

from functools import wraps

def overloaded(func):
    def overloaded_func(*args, **kwargs):
        for f in overloaded_func.overloads:
                return f(*args, **kwargs)
            except TypeError:
            # it will be nice if the error message prints a list of
            # possible signatures here
            raise TypeError("No compatible signatures")

    def overload_with(func):
        return overloaded_func

    overloaded_func.overloads = [func]
    overloaded_func.overload_with = overload_with
    return overloaded_func


def a():
    print 'a() without args'

def _(n):
    # note that, just like property(), the function's name in
    # the "def _(n):" line can be arbitrary, the important
    # name is in the "@overloads(a)" line
    print 'a() with args'

a(4, 5) # ERROR: no matching signature

PS: I posted the code to recipe book, for future reference:

More information about the Python-list mailing list