Is it an iterator? (was Re: FixedPoint)
Aahz Maruch
aahz at panix.com
Fri Feb 8 14:13:30 EST 2002
In article <GJS88.49612$3J1.1396553 at news2.tin.it>,
Alex Martelli <aleax at aleax.it> wrote:
>
>"something is iterable" if and only if you can iterate on it. So, try
>iterating on it, and handle the resulting exception should it turn out
>you can't. I'm not sure exactly what exceptions would be raised by
>various versions of Python -- probably a TypeError, but one never
>knows -- better to experiment on all relevant versions, or maybe, just
>for once, a generic try/except is acceptable. An almost acceptable
>version might therefore be:
>
>def isIterable(x):
> try:
> for i in x: return 1 # iterable
> else: return 1 # iterable, although empty
> except:
> return 0
>
>Unfortunately, if we're in Python 2.2 and x is an iterator, isIterable
>"consumes" x's first item. This isn't hard to fix:
>
>def isIterable(x):
> try: x=iter(x)
> except: pass
> else: return 1
> try:
> for i in x: return 1 # iterable
> else: return 1 # iterable, although empty
> except:
> return 0
This still breaks with files, I believe (don't have 2.2 handy to test).
--
--- Aahz <*> (Copyright 2002 by aahz at pobox.com)
Hugs and backrubs -- I break Rule 6 http://www.rahul.net/aahz/
Androgynous poly kinky vanilla queer het Pythonista
"We should forget about small efficiencies, about 97% of the time.
Premature optimization is the root of all evil." --Knuth
More information about the Python-list
mailing list