How to tell the difference between string and list
bokr at oz.net
Fri Dec 5 19:20:20 CET 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
> 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 + 'ghi'
['abc', 'def', 'ghi']
>>> def isstringlike(x):
... try: x+""
... except TypeError: return False
... else: return 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'
['abc', 'def', 'g', 'h', 'i']
More information about the Python-list