Test for structure

Steven Bethard steven.bethard at gmail.com
Sun Feb 20 17:36:19 EST 2005


Terry Hancock wrote:
 > But you probably shouldn't do that. You should probably just test to
 > see if the object is iterable --- does it have an __iter__ method?
 >
 > Which might look like this:
 >
 > if hasattr(a, '__iter__'):
 >     print "'a' quacks like a duck"

Martin Miller top-posted:
> I don't believe you can use the test for a __iter__ attribute in this
> case, for the following reason:
> 
>>>>c1 = 'abc'
>>>>c2 = ['de', 'fgh', 'ijkl']
>>>>hasattr(c1, '__iter__')
> False
> 
>>>>hasattr(c2, '__iter__')
> True

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

Another lesson in why EAPF is often better than LBYL in Python[1].

STeVe

[1] http://www.python.org/moin/PythonGlossary



More information about the Python-list mailing list