[Python-ideas] Make functools.singledispatch register method return original function.

Mital Ashok mital.vaja at googlemail.com
Sat Jun 17 17:27:47 EDT 2017


Right now, an example for single dispatch would be:

from functools import singledispatch

@singledispatch
def fun(arg, verbose=True):
    if verbose:
        print("Let me just say,", end=" ")
    print(arg)

@fun.register(int)
def _(arg, verbose=True):
    if verbose:
        print("Strength in numbers, eh?", end=" ")
    print(arg)

@fun.register(list)
def _(arg, verbose=True):
    if verbose:
        print("Enumerate this:")
    for i, elem in enumerate(arg):
        print(i, elem)

But this makes a useless _ function, that should either be deleted or
ignored. For properties, a common pattern is this:

class Foo:
    @property
    def bar(self):
        return self._bar

    @bar.setter
    def bar(self, value):
        self._bar = value

So I'm suggesting that @function.register for single dispatch
functions returns the same function, so you would end up with
something like:

@singledispatch
def fun(arg, verbose=True):
    if verbose:
        print("Let me just say,", end=" ")
    print(arg)

@fun.register(int)
def fun(arg, verbose=True):
    if verbose:
        print("Strength in numbers, eh?", end=" ")
    print(arg)

And to get back the old behaviour, where you can get the function
being decorated, just call it afterwards:

@singledispatch
def fun(arg, verbose=True):
    if verbose:
        print("Let me just say,", end=" ")
    print(arg)

def used_elsewhere(arg, verbose=True):
    if verbose:
        print("Strength in numbers, eh?", end=" ")
    print(arg)

fun.register(int)(used_elsewhere)

But this goes against what a single-dispatch function is, so I think
this is a minor enough use case to not worry about.


More information about the Python-ideas mailing list