[Python-ideas] Why not ['a','b','c'].join(',') ?

Chris Angelico rosuav at gmail.com
Sun Mar 24 12:01:45 EDT 2019


On Mon, Mar 25, 2019 at 12:28 AM Jonathan Fine <jfine2358 at gmail.com> wrote:
>
> Disclaimer: I've not recently read any discussions of this topic. And everything I say is my own opinion.
>
> SUMMARY
> The syntax of Python's string join operator are a consequence of Python's core design decisions and coding principles, together with the semantics of join. I'll explain this in a series of posts.
>
> Why str.join? Wouldn't list.join be better?
> ===============================
> Python variables don't have types. Python objects do have types. When writing Python, don't test for the type of an object, unless you have to. Instead, test to see if the object has the methods you need.
>
> Eg help(dict.update)
> update(...)
>     D.update([E, ]**F) -> None.  Update D from dict/iterable E and F.
>     If E is present and has a .keys() method, then does:  for k in E: D[k] = E[k]
>     If E is present and lacks a .keys() method, then does:  for k, v in E: D[k] = v
>     In either case, this is followed by: for k in F:  D[k] = F[k]
>
> Now for the semantics of string join. By Python principles
>     From a str and an iterable
>     The string join operator
>      Produces a str
>
> You question amounts to this. Should the signature be
>     (str, iterable) -> str    # Informal type signature of join.
> or should it be
>     (iterable, str) -> str
>
> At first glance, there's no way of choosing. But in Python we prefer
>     aaa.join(bbb)
> to
>     from somewhere import join
>     join(aaa, bbb)
>
> So the question now becomes: Choose between
>     str.join(iterable)
>     iterable.join(str)
>
> There is some sense in having list.join. But in Python, we can't join the elements of a list without getting an iterable from the list (unless there's something like very special short-cut-semantics built into Python).
>
> So in Python the choice is between
>     str.join(iterable)
>     iterable.join(str)
>
> Now str.join looks more attractive. But I said, without thinking ahead, that the syntax of Python's string join operator is a consequence of Python's core design decisions and coding principles, together with the semantics of join.
>
> I'm not quite there yet, there's a gap to fill.  I'll pause for a day or two now, just in case someone else wants to JOIN in the discussion, and perhaps fill the gap.
>

It's way WAY simpler than all this. "Iterable" isn't a type, it's a
protocol; in fact, "iterable" just means "has an __iter__ method".
Adding a method to iterables means adding that method to every single
object that wants to be iterable, but adding a method to strings just
means adding it to the str type.

And, this is a topic for python-list, not python-ideas, unless someone
is proposing a change.

ChrisA


More information about the Python-ideas mailing list