[Python-ideas] The non-obvious nature of str.join (was Re: sum(...) limitation)
Nick Coghlan
ncoghlan at gmail.com
Wed Aug 13 07:50:13 CEST 2014
On 13 August 2014 14:38, Stephen J. Turnbull <stephen at xemacs.org> wrote:
> Wolfgang Maier writes:
>
> > Exactly. So my point was that when you don't subclass str, but instead
> > use a wrapper around it, you can give it a as str-like interface as you
> > want so the thing looks and feels like a string to users, it will still
> > not work as part of an iterable passed to .join
>
> You mean this behavior?
>
> wideload:~ 12:42$ python3.2
>>>>
> ...
>>>> class N:
> ... def __init__(self, s=''):
> ... self.s = s
> ... def __str__(self):
> ... return self.s
> ...
>>>> " ".join(['a', N('b')])
> Traceback (most recent call last):
> File "<stdin>", line 1, in <module>
> TypeError: sequence item 1: expected str instance, N found
>>>> ' '.join(str(x) for x in ['a', N('b')])
> 'a b'
>>>>
>
> Given the fact that every object is str-able, I don't think we want to
> give "str(x) for x in" semantics to str.join. So I think the answer
> is "if you want Nasty to automatically acquire all the behaviors of
> str, make it a subclass of str".
Note that this is a general problem - it is quite common to use
explicit type checks against str rather than relying on ducktyping. In
theory, a suitable ABC could be defined (using collections.UserString
as a starting point), but nobody has ever found it a pressing enough
problem to take the time to do so - it's generally easier to just
inherit from str.
Cheers,
Nick.
--
Nick Coghlan | ncoghlan at gmail.com | Brisbane, Australia
More information about the Python-ideas
mailing list