[Python-ideas] Another attempt at a sum() alternative: the concatenation protocol

Nick Coghlan ncoghlan at gmail.com
Tue Jul 16 08:50:32 CEST 2013


I haven't been following the sum() threads fully, but something Ron
suggested gave me an idea for a concatenation API and protocol. I
think we may also be able to use a keyword-only argument to solve the
old string.join vs str.join problem in a more intuitive way.

    def concat(start, iterable, *, interleave=None):
        try:
            build = start.__concat__
        except AttributeError:
            result = start
            if interleave is None:
                for x in iterable:
                    result += x
            else:
                for x in iterable:
                    result += interleave
                    result += x
        else:
            result = build(iterable, interleave=interleave)

If implementing this as a third party API you'd use a tool like
functools.singledispatch (which has a backport available on PyPI)
rather than defining a new protocol. Registering implementations for
the immutable builtin types like str, bytes and tuple would then allow
those to be handled efficiently, just as if they provided appropriate
__concat__ implementations.

A simple "use sum for numbers, concat for containers" approach is
simpler and clearer than trying to coerce sum into being fast for both
when its assumptions are thoroughly grounded in manipulating numbers
rather than containers.

Cheers,
Nick.

--
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia


More information about the Python-ideas mailing list