Argument against iterable ints...
James Althoff
jamescalthoff at yahoo.com
Sat Apr 6 13:29:02 EST 2002
[Magnus Lie Hetland]
> Just a situation that cropped up recently: While writing a little
> generator for flattening nested iterables, I used
>
> try: iter(foo)
> except: return foo
> else:
> ....
>
> (of course I could have used a for loop directly in the try clause --
> that doesn't change anything.)
>
> If integers became iterable, this sort of code would suddenly become
> infinitely recursive. Given the propensity for using exceptions in
> this manner rather than type checking in Python, this seems like a
> weighty argument to me...
Magnus,
I don't see how the above is even recursive, much less infinitely recursive.
Could you elaborate?
Also, note that the final, rejected (finally rejected ;-) version of PEP 276
suggests an alternative to adding an iterator to class int (even though such
a simple method addition was what motivated the original idea). The
alternative would be (would have been) to change the code in the for-loop
implementation to add a conceptual two-liner:
if isinstance(iter_target,int):
iter_target = xrange(iter_target)
Doing so would make
for i in 5:
a simpler, less-cluttered spelling of
for i in xrange(5):
and therefore would allow the "flatter is better than nested"
for i in len(L):
as a substitute for the more nested, less flat
for i in xrange(len(L)):
And it would prevent all problems with an integer iterator popping up in
undesirable circumstances -- since there would be no such iterator.
Jim
More information about the Python-list
mailing list