How to tell the difference between string and list

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


On 05 Dec 2003 17:03:35 +0000, jjl at pobox.com (John J. Lee) wrote:

>Jan Kokoska <kokoska.jan at globe.cz> writes:
>
>> I need to recognize 'var' and ['var'], usually I would use:
>[...]
>
>All the other solutions posted are bad because they fail for
>user-defined string-like classes (unless those classes use the new 2.2
>features by deriving from str or unicode).  As long as your strings
>aren't huge:
>
>def isstringlike(x):
>    try: x+""
>    except TypeError: return False
>    else: return True
>
>
>I think I stole this off Alex Martelli.
>
There are some caveats in using that re side effects and unanticipated semantics,
e.g., a contrived example of both:

 >>> class Slist(list):
 ...     def __add__(s, o):
 ...         if isinstance(o, str): print '<<side effect!!>>'; return list.__add__(s,[o])
 ...         return list.__add__(s,o)
 ...
 >>> sl = Slist(['abc','def'])
 >>> sl
 ['abc', 'def']
 >>> sl + 'ghi'
 <<side effect!!>>
 ['abc', 'def', 'ghi']
 >>> def isstringlike(x):
 ...     try: x+""
 ...     except TypeError: return False
 ...     else: return True
 ...
 >>> sl
 ['abc', 'def']
 >>> isstringlike(sl)
 <<side effect!!>>
 True

Is it? IMO, no. Accepting addition of strings does not a string make. You can't
assume anything about the result or the object except that string addition is defined.

The side effect here is contrived, but adding a string to a list could be handy
if you have a list-like object that deals with strings and might not want the
behavior of an ordinary list, which is:

 >>> s2 = ['abc','def']
 >>> s2 + 'ghi'
 Traceback (most recent call last):
   File "<stdin>", line 1, in ?
 TypeError: can only concatenate list (not "str") to list
 >>> s2 += 'ghi'
 >>> s2
 ['abc', 'def', 'g', 'h', 'i']

Regards,
Bengt Richter




More information about the Python-list mailing list