what should __iter__ return?

MRAB python at mrabarnett.plus.com
Fri Sep 3 16:02:35 EDT 2010


On 03/09/2010 20:35, ernest wrote:
> Hi,
>
> What is better:
>
> def __iter__(self):
>      for i in len(self):
>          yield self[i]
>
> or
>
> def __iter__(self):
>      return iter([self[i] for i in range(len(self))])
>
> The first one, I would say is more correct,
> however what if in a middle of an iteration
> the object changes in length? Then, the
> iterator will fail with IndexError (if items
> have been removed), or it will fail to iterate
> over the whole sequence (if items have
> been added).
>
> What do you think?
>
I'd say the first one is less correct because you can't iterate over an
int. :-)



More information about the Python-list mailing list