[Python-Dev] Single- vs. Multi-pass iterability
Andrew Koenig
ark@research.att.com
Mon, 15 Jul 2002 20:32:36 -0400 (EDT)
>> However the purpose my suggestion of __multiter__ was not to use it to
>> test for multiple iteration, but to enable a container to be able to
>> yield either a single or a multiple iterator on request.
David> Why would you want that? Seems like a corner case at best.
You're right -- I wasn't thinking clearly.
What I meant to say was that I would like a program that expects
to be able to use a multiple iterator to be able to say so simply
and efficiently in code. For example:
for i in multiter(x):
// whatever
I would like this to fail cleanly if x does not support multiple
iterators.
>> A data structure that supports several different kinds of iteration
>> has to provide that support somehow. What's your suggestion?
David> class DataStructure(object):
David> def __init__(self):
David> self._numbers = range(10);
David> self._names = [ str(x) for x in range(10) ];
David> names = property(lambda self: iter(self._names))
David> numbers = property(lambda self: iter(self._numbers))
David> x = DataStructure();
David> for y in x.names:
David> print repr(y),
David> print
David> for y in x.numbers:
David> print repr(y),
David> [Y'know, Python is great. That worked the first time I ran it.]
I don't understand how this code answers my question.
You've asked for iterators over two different data structures.
What I was asking was, for example, how one might arrange for a single
tree to yield either a depth-first or breadth-first iterator.