[Python-Dev] PEP 443 - Single-dispatch generic functions (including ABC support)

Łukasz Langa lukasz at langa.pl
Fri May 31 01:47:59 CEST 2013

On 29 maj 2013, at 04:40, Nick Coghlan <ncoghlan at gmail.com> wrote:

> I expect we will see improved tools for integrating class based
> dispatch and generic function dispatch in the future, but we should
> *not* try to engineer a solution up front. Doing so would involve too
> much guessing about possible use cases, rather than letting the design
> be informed by the *actual* use cases that emerge in practice.

I thought about this over the last two days and I've concluded Nick
is right here. I really don't want functools.singledispatch to be
undercooked when introduced. However, it seems we fleshed out the PEP
and the reference implementation to do one thing only, and do it well.
The rest is guesswork. It's better to build on a simple foundation than
to provide a solution waiting for the problem (see: annotations).

So, unless anyone strongly objects, I think we shouldn't bother to
special-case instance methods and class methods.

"Code wins arguments":

class State:
    def __init__(self):
        self.add.register(int, self.add_int)
        self.add.register(float, self.add_float)
        self.add.register(complex, self.add_complex)
        self.sum = 0

    def add(arg):
        raise TypeError("This type is not supported.")

    def add_int(self, arg):
        self.sum += arg

    def add_float(self, arg):
        self.sum += int(round(arg))

    def add_complex(self, arg):
        self.sum += int(round(arg.real))

if __name__ == '__main__':
    state = State()
    assert state.sum == 8
    assert state.sum == 10
        assert False, "TypeError not raised."
    except TypeError:
        pass   # properly refused to add a string

Best regards,
Łukasz Langa

WWW: http://lukasz.langa.pl/
Twitter: @llanga
IRC: ambv on #python-dev

More information about the Python-Dev mailing list