Test for structure

Martin Miller ggrp1.20.martineau at dfgh.net
Sun Feb 20 17:08:07 EST 2005


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
>>> for i in c1: print "i=%s is an element of c1" % repr(i)
...
i='a' is an element of c1
i='b' is an element of c1
i='c' is an element of c1

In other words, even though the c1 single string variable does not have
an __iter__ attribute, it can still be used in a for loop. I think the
right answer would depend on what exactly the OP intends to do with the
argument when it is a list (or is list-like in some way) -- i.e. he
didn't say specifically that he wanted use it in a for loop.

-Martin


====================
Terry Hancock wrote:
> On Wednesday 16 February 2005 09:08 am, alex wrote:
> > how can I check if a variable is a structure (i.e. a list)? For my
> > special problem the variable is either a character string OR a list
of
> > character strings line ['word1', 'word2',...]
> >
> > So how can I test if a variable 'a' is either a single character
string
> > or a list?
>
> The literally correct but actually wrong answer is:
>
> if type(a) == type([]):
>     print "'a' is a duck"
>
> 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"
>
> That way your function will also work if a happens to be a tuple,
> a dictionary, or a user-defined class instance which is happens to
> be  iterable.
>
> Being "iterable" means that code like:
>
> for i in a:
>    print "i=%s is an element of a" % repr(i)
>
> works.  Which is probably why you wanted to know, right?
>
> Cheers,
> Terry
>
> --
> --
> Terry Hancock ( hancock at anansispaceworks.com )
> Anansi Spaceworks  http://www.anansispaceworks.com




More information about the Python-list mailing list