string.join() syntax quirky?

Fredrik Lundh fredrik at pythonware.com
Tue Nov 27 08:35:02 EST 2001


Russell E. Owen wrote:
> One way to look at it is that the various collection classes do NOT
> inherit from a single base class (which would be a logical place to
> define a join method).

Footnote: join takes a sequence, not a collection.  Sequences
are defined by an informal protocol, not a base class.

> Hence to have all kinds of collections learn to "join" requires a lot of
> repeat coding. Making join a string method solves this problem.

If you look at this from the implementation perspective (I wrote
that code), and try to take everything into account, it's obvious
that the separator is the only thing that we can rely on for the
dispatch.  You cannot dispatch on the type of the sequence
(because it's not a type!), and you cannot dispatch on the first
element (the sequence may be empty).  And forcing the user to
use different join function for different string types didn't feel
right.

So the first implementation did something like this:

    # from string.py
    def join(seq, sep=" "):
        return sep.__join__(seq, sep)

where the first sep was only used to quickly find the internal
join implementation, without having to figure out what module
to import.  In the next iteration, I removed the extra argument:

    def join(seq, sep=" "):
        return sep.__join__(seq)

...and from there, it was only a matter of minutes before someone
argued that "why bother using a secret name; people will find out
anyway", leaving us with:

    def join(seq, sep=" "):
        return sep.join(seq)

(fwiw, you'll hardly ever find the sep.join(seq) form in my code)

</F>

<!-- (the eff-bot guide to) the python standard library:
http://www.pythonware.com/people/fredrik/librarybook.htm
-->





More information about the Python-list mailing list