[ACCEPTED]-python list __iter__ method called on every loop?-python-2.6

Accepted answer
Score: 12

You can simply return a generator expression 4 from __iter__()

class MyList(list):
    def __iter__(self):
        return (self.do_something(x) for x in list.__iter__(self))

    def do_something(self, x):
        print 'do something', x
        return x

my_list = MyList(range(10))
print my_list

for item in my_list:
    print item

ncoghlan suggests using a generator 3 in place of the generator expression which 2 makes for easier debugging

class MyList(list):

    def __iter__(self):
        for x in list.__iter__(self):
            yield self.do_something(x)

    def do_something(self, x):
        print 'do something', x
        return x

my_list = MyList(range(10))
print my_list

for item in my_list:
    print item

alternatively 1 you could use imap here

from itertools import imap

class MyList(list):
    def __iter__(self):
        return imap(self.do_something, list.__iter__(self))

    def do_something(self, x):
        print 'do something', x
        return x


my_list = MyList(range(10))
print my_list

for item in my_list:
    print item
Score: 4

__iter__ returns an iterator object. If you need to do something 3 in every iteration, you have to implement 2 your own (it has to implement two methods 1 described in the linked docs).

Score: 3

The python class __iter__() method actually returns 5 an iterator object. See the following for 4 reference: http://docs.python.org/library/stdtypes.html#iterator-types

On the iterator object the next() method 3 will be called on each step of the loop. You 2 could write a custom iterator which would 1 be returned by your custom list.

Score: 0

I want the elements of the list to be initialized/finalized 16 with every loop of the list

A list has no 15 direct control over this. Several loops 14 can access a list in parallel (e.g. in nested 13 loops). Each loop is controlled by an iterator, and 12 __iter__() should return iterators, every time it's 11 called. You can't return the same iterator 10 instance all the time, because said parallel 9 loops will then interfere with each other.

But 8 inside an iterator you're free to instantiate 7 items as you need. Finalizing them from 6 inside the iterator is hardly wise, because 5 once you returned an item, you lost control 4 over it. If you finalize it at a later moment, outer 3 code that still relies on the item may fail. If 2 you need to finalize your items, make it 1 a responsibility of items' consumer.

More Related questions