On 29 maj 2013, at 04:40, Nick Coghlan <ncogh...@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

    @staticmethod
    @singledispatch
    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()
    state.add(1)
    state.add(2.51)
    state.add(3.7+4j)
    assert state.sum == 8
    state.add(2.50)
    assert state.sum == 10
    try:
        state.add("string")
        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

_______________________________________________
Python-Dev mailing list
Python-Dev@python.org
http://mail.python.org/mailman/listinfo/python-dev
Unsubscribe: 
http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com

Reply via email to