What makes an iterator an iterator?

Steven D'Aprano steve at REMOVEME.cybersource.com.au
Wed Apr 18 04:32:15 EDT 2007


On Wed, 18 Apr 2007 06:13:39 +0000, I V wrote:

> On Wed, 18 Apr 2007 15:39:22 +1000, Steven D'Aprano wrote:
>> I thought that an iterator was any object that follows the iterator
>> protocol, that is, it has a next() method and an __iter__() method.

[snip]

> i.e., just rename your _next function to __iter__ . Your class won't
> itself be an iterator, but it will be usable in for statements and so one,
> and convertable to an iterator with the iter builtin.


Thanks to all those who helped, this fixed my problem.

For the record, this is what I actually wanted: a four-line self-sorting
dictionary:

class SortedDict(dict):
    def __iter__(self):
        for key in sorted(self.keys()):
            yield key

Note that using sorted(self) does not work.

Iterating over a SortedDictionary returns the keys in sorted order. This
minimalist implementation doesn't sort the values, items or string
representation of the dict, but they should be easy to implement.



-- 
Steven D'Aprano 




More information about the Python-list mailing list