Sending to the list, originally this went just to Marcus...
Marcus Goldfish wrote:
I'm trying to understand custom iterators in Python, and created the following toy class for sequence comparison, which seems to work:
class Foo(object): """A toy class to experiment with __eq__ and __iter__""" def __init__(self, listA, listB): self.head, self.tail = listA, listB def __iter__(self): return iter(self.head[:]+self.tail[:]) def __eq__(self, other): """Foo instances are equal if their respective subsequences, head, tail, are in the same order""" diff = [i for i, j in zip(self, other) if i != j] return len(diff) == 0
I'm not really sure if I'm implementing iter() correctly, for instance: should I make copies of the sublists? Should I try to implement my own next() method?
A few comments: - A semantic point - you haven't created a custom iterator, you have created a class that is iterable. The actual iterator is the standard list iterator.
- You actually copy head and tail twice in __iter__ - once explicitly with [:] and once with + which makes a new list. Neither copy is needed.
- As Rich pointed out, making Foo into it's own iterator by adding a next() method is not a good idea. A simple way to define your own iterator is to make __iter__() into a generator function like this: def __iter__(self): for i in self.head: yield i for i in self.tail: yield i
- __eq__() will say that Foo([1,2], [3,4]) == [1,2,3,4] which may not be what you want. If not then put in a test for isinstance(other, Foo)
- __eq__() will say that Foo([1], [2]) == Foo([1, 2], []) which may not be what you want. A simple definition for __eq__() that finds these unequal would be def __eq__(self, other): return self.head == other.head and self.tail == other.tail
- If you define __eq__() you should also define __ne__(). Alteratively you can define __cmp__().
Reference on iterators: http://docs.python.org/lib/typeiter.html
Reference on __eq__(): http://docs.python.org/ref/customization.html
Kent
_______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor