How clean/elegant is Python's syntax?

Chris Angelico rosuav at gmail.com
Fri May 31 14:52:53 EDT 2013


On Sat, Jun 1, 2013 at 1:43 AM, Ian Kelly <ian.g.kelly at gmail.com> wrote:
> On Thu, May 30, 2013 at 1:38 PM, MRAB <python at mrabarnett.plus.com> wrote:
>> And additional argument (pun not intended) for putting sep second is
>> that you can give it a default value:
>>
>>    def join(iterable, sep=""): return sep.join(iterable)
>
> One argument against the default is that it is specific to the str
> type.  If you then tried to use join with an iterable of bytes objects
> and the default sep argument, you would get a TypeError.  At least not
> having the default forces you to be explicit about which string type
> you're joining.

What about:

def join(iterable, sep=None):
    if sep is not None: return sep.join(iterable)
    iterable=iter(iterable)
    first = next(iterable)
    return first + type(first)().join(iterable)

Granted, it has some odd error messages if you pass it stuff that isn't strings:

>>> join([[1,2,3],[4,5,6]])
Traceback (most recent call last):
  File "<pyshell#241>", line 1, in <module>
    join([[1,2,3],[4,5,6]])
  File "<pyshell#235>", line 5, in join
    return first + type(first)().join(iterable)
AttributeError: 'list' object has no attribute 'join'

but you'd get that sort of thing anyway.

(NOTE: I am *not* advocating this. I just see it as a solution to one
particular objection.)

ChrisA



More information about the Python-list mailing list