Supporting list()

Dave Angel d at davea.name
Mon Dec 17 15:55:15 CET 2012


On 12/17/2012 09:33 AM, Skip Montanaro wrote:
> What method(s) does a class have to support to properly emulate a container
> which supports turning it into a list?  For example:
>
>   class Foo:
>     pass
>
>   f = Foo()
>   print list(f)
>
> Is it just __iter__() and next()?  (I'm still using 2.4 and 2.7.)

I believe the container class needs to define the __iter__() method,
which has to return an iterator object.

That (possibly different) iterator class needs both an __iter__() method
and a next() method.

If the container class is also the iterator class, which is common, then
you just need one __iter__() method, which returns self.



-- 

DaveA




More information about the Python-list mailing list