How to tell the difference between string and list
John J. Lee
jjl at pobox.com
Sat Dec 6 16:48:27 CET 2003
bokr at oz.net (Bengt Richter) writes:
> On 05 Dec 2003 20:24:02 +0000, jjl at pobox.com (John J. Lee) wrote:
> >bokr at oz.net (Bengt Richter) writes:
> >> >>> s2 = ['abc','def']
> >> >>> s2 += 'ghi'
> >> >>> s2
> >> ['abc', 'def', 'g', 'h', 'i']
> >That's not what the code I posted tests for.
> You mean __iadd__? I know, I was just showing ordinary list
> behavior, and showed that as well to imply that that's also
> something you might want to override in a consistent way if you were
> overriding __add__ as in my example.
What? list.__add__(self, "") raises TypeError, which means lists do
work OK with isstringlike().
> Don't forget, an object's __add__ could be defined to accept
> _anything_ for addition, and a string would just be a generic thing,
> whose stringness was really irrelevant to the adding object. Are you
> making other assumptions based on isstringlike?
That's true: especially given the sequence-ness of strings, which was
the whole motivation for this function in the first place! In fact,
isstringlike(UserList()) is true. Bah.
> If so, I think those assumptions should be an explicit part of the
> test, or you are setting yourself up for using the test and assuming
> the wrong things about some object. You can say you'll use
> exceptions will sort those things out,
Well, sometimes that's just the problem: exceptions *won't* get
raised, because strings are sequences.
I guess it's all depends on the particular case. :-(
More information about the Python-list