Test for structure

Steven Bethard steven.bethard at gmail.com
Mon Feb 21 13:39:14 EST 2005


 > Steven Bethard wrote:
 >>
 >>Right.  str and unicode objects support iteration through the old
 >>__getitem__ protocol, not the __iter__ protocol.  If you want to use
 >>something as an iterable, just use it and catch the exception:
 >>
 >>try:
 >>     itr = iter(a)
 >>except TypeError:
 >>     # 'a' is not iterable
 >>else:
 >>     # 'a' is iterable

Martin Miller broke the order of reading by top-posting:
> In either case, you can't tell a string and list apart, which is what
> the OP wanted to know, namely how to differentiate the two.

Yes, sorry, I should have marked my post OT.  It was an answer to Terry 
Hancock's post suggesting hasattr(x, '__iter__'), not the OP.

> Perhaps the test for an __iter__ attribute *is* the way to go because
> you can tell the difference between the two type.

I've seen this done before, e.g.:

try:
     itr = iter(x)
except TypeError:
     # is not iterable
else:
     if hasattr(x, '__iter__'):
         # is other iterable
     else:
         # is str or unicode

I don't like this idea much because it depends on str and unicode _not_ 
having a particular function.  I haven't seen any guarantee anywhere 
that str or unicode won't ever grow an __iter__ method.  So this code 
seems dangerous as far as future compatibility goes.

> I think the technique suggested by Robin Munn nearly a year ago (and
> referenced by the link in Simon Brunning's post):
> http://groups-beta.google.com/group/comp.lang.python/msg/c8befd4bed517bbc
> namely:
> 
> try:
>     a + ''
> except TypeError:
>     pass
> else:
>     a= [a]
> 
> would be a good usable solution, although it's not totally infallible.

Yup, if I had to do this kind of type-checking (which I don't think I 
ever do), I'd probably go with something along these lines.

STeVe



More information about the Python-list mailing list