How can I verify that a passed argument is an interible collection?
John Machin
sjmachin at lexicon.net
Thu Apr 21 18:31:29 EDT 2005
On Thu, 21 Apr 2005 09:59:54 -0500, Larry Bates
<lbates at syscononline.com> wrote:
>2) Or if you not you could see if the argument has next and
>__iter__ methods (more general solution)
>
>if hasattr(arg, 'next') and not hasattr(arg, '__iter__'):
> # perform work on iterable
>
>else:
> print "arg must be an iterable"
>
>>> alist = ['Think', 'before', 'posting!']
>>> hasattr(alist, 'next')
False
===>>> Fails the first leg of your test for iterability.
>>> for wd in alist:
... print wd
...
Think
before
posting!
===>>> Looks iterable to me!!
In any case, trying to define "isiterable(x)" in terms of x having or
not having particularly-named attributes doesn't seem to me to be a
very good idea. It's what the method *does* that matters. Other ways
of doing it may be invented. Such a definition has about the same
level of future-proof correlation between cause and effect as "We
waved a dead chicken at the volcano and it stopped erupting".
Cheers,
John
More information about the Python-list
mailing list