I have a function that take an argument which can be either a single item or a double item:
def iterable(arg)
if #arg is an iterable:
print "yes"
else:
print "no"
so that:
>>> iterable( ("f","f") )
yes
>>> iterable( ["f","f"] )
yes
>>> iterable("ff")
no
The problem is that string is technically iterable, so I can’t just catch the ValueError when trying arg[1]. I don’t want to use isinstance(), because that’s not good practice (or so I’m told).
Use isinstance (I don’t see why it’s bad practice)
Note the use of StringTypes. It ensures that we don’t forget about some obscure type of string.
On the upside, this also works for derived string classes.
Also, you might want to have a look at this previous question.
Cheers.
NB: behavior changed in Python 3 as
StringTypesandbasestringare no longer defined. Depending on your needs, you can replace them inisinstancebystr, or a subset tuple of(str, bytes, unicode), e.g. for Cython users.As @Theron Luhn mentionned, you can also use
six.