How to tell the difference between string and list

Bengt Richter bokr at oz.net
Fri Dec 5 20:22:56 EST 2003


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.

>
>And the fact that having a+b not raise TypeError breaks that function
>seems to me to be a good reason not to do that.

Convince me ;-) _Any_ object with an __add__ method that
does not exclude a string as a thing to add would pass your/Alex's
isstringlike test. IMO that's too big a set of unanticipatable possibilites.
Do you really want to dictate "never accept a str instance as other in __add__(self, other)" ;-)

What do you want to be able to assume about an object obj for which isstringlike(obj)
returns True, besides that it accepts strings for addition? Do you want to make those
additional assumptions requirements for all objects that do pass the isstringlike test?
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?
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,
but then why pre-screen for stringlikeness? You may have a use case,
but I suspect it will be context-dependent.

The test is fine in a context where you can reasonably anticipate the
mix of objects to be tested, but as a universal test, I would say
s/isstringlike/willaddstrings/ or perhaps
s/isstringlike/willaddatleastonestringbutyoumayhaveusedupthequota/ ;-)

Regards,
Bengt Richter




More information about the Python-list mailing list