Why doesn't join() call str() on its arguments?

Leif K-Brooks eurleif at ecritters.biz
Thu Feb 17 07:46:00 EST 2005


Leo Breebaart wrote:
> What I can't find an explanation for is why str.join() doesn't
> automatically call str() on its arguments

I don't really like that idea for the reasons others have stated. But a 
related and (IMHO) more Pythonic idea would be to allow arbitrary 
objects to be str.join()ed if they use __radd__ to allow concatenation 
with strings. This would be consistent with how the + operator behaves:

Python 2.4 (#2, Jan  8 2005, 20:18:03)
[GCC 3.3.5 (Debian 1:3.3.5-5)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
 >>> class Foo(object):
...     def __radd__(self, other):
...         if isinstance(other, basestring):
...             return other + str(self)
...     def __str__(self):
...         return 'Foo()'
...
 >>> 'foo:' + Foo()
'foo:Foo()'
 >>> ''.join(['foo', Foo()])
Traceback (most recent call last):
   File "<stdin>", line 1, in ?
TypeError: sequence item 1: expected string, Foo found



More information about the Python-list mailing list