Argument against iterable ints...
James Althoff
jamescalthoff at yahoo.com
Sun Apr 7 16:03:42 EDT 2002
[Magnus Lie Hetland]
> def flatten(seq):
> try: iter(seq)
> except: yield seq
> else:
> for sub in seq:
> for item in flatten(sub):
> yield item
>
> Anyway, I guess I shouldn't frame this as an argument against the
> rejected PEP <snip>
Indeed. Especially since the referred to infinite recursion is *not* a
problem with iterable ints!
I believe you are referring to the following issue:
>>> iter('a').next() == 'a'
1
>>> iter('a').next() == iter(iter('a').next()).next()
1
>>>
This situation does not arise for iterable ints -- which we can simulate
with xrange as in:
>>> iter(xrange(0)).next() == 0
Traceback (most recent call last):
File "<stdin>", line 1, in ?
StopIteration
>>>
This is because iter(n) returns (hypothetically speaking, of course ;-) 0,
1, . . ., n - 1, "raise StopIteration" -- meaning *only* "raise
StopIteration" happens for iter(0).next(). (And other positive ints
eventually "count down" to 0).
Note the following simulation:
>>> from __future__ import generators
>>>
>>> def flatten(seq):
... try: isinstance(seq,int) or iter(seq)
... except: yield seq
... else:
... if isinstance(seq,int):
... iterator = iter(xrange(seq))
... else:
... iterator = iter(seq)
... for sub in iterator:
... for item in flatten(sub):
... yield item
...
>>> list(flatten(4))
[]
>>>
Notice that there is no infinite recursion for integers.
But you did uncover an interesting issue with *strings* and iterators! :-)
Jim
More information about the Python-list
mailing list