[Tutor] Iterator vs. iterable cheatsheet, was Re: iter class

spir denis.spir at gmail.com
Fri Jan 24 23:23:26 CET 2014


On 01/24/2014 06:44 PM, Peter Otten wrote:
> There is no infinite recursion. The for loop is currently implemented as
>
> # expect an iterable
> # handle iterators through an idempotent iter()
> tmp = iter(xs)

# here you must check that tmp actually implements the iterator protocol,
# else raise an error

> while True:
>      try:
>          x = next(tmp)
>      except StopIteration:
>          break
>      # use x
>
> If I understand you correctly you suggest the following:
>
> # expect an iterator
> # fall back to getting an iterator through iter()
> try:
>      tmp = xs.__next__
> except AttributeError:
>      tmp = iter(xs).__next__
> while True:
>      try:
>          x = tmp()
>      except StopIteration:
>          break
>
> How is that simpler?

see above

d


More information about the Tutor mailing list