[Python-3000] Iterators for dict keys, values, and items == annoying :)
Guido van Rossum
guido at python.org
Fri Mar 24 00:41:37 CET 2006
On 3/23/06, Ian Bicking <ianb at colorstudy.com> wrote:
[Guido]
> > Testing whether an iterator is empty or not is an oxymoron; the only
> > legit way is to call next() and see whether it raises StopIteration.
> > This is the fundamental confusion I am talking about. It is NOT
> > "natural enough". It reveals a fundamental misunderstanding of the
> > design of the iterator protocol.
>
> I'm talking about a use case, not the protocol. Where iterators are
> used, it is very common that you also want to distinguish between zero
> and some items.
Really? Methinks you are thinking of a fairly specific context -- when
presenting database query results to a user. The problem IMO lies in
SQLObject (which I admit I've never used) or perhaps in SQL itself, or
the specific underlying DB. In most other situations, you have an
honest-to-god container (e.g. a dict) which you can test for emptiness
before even asking for an iterator over its items. When all you have
is a query represented as an iterator this doesn't fly. That's why
some DB API implementations return the number of results as the
non-standard return value of the query API (at least that's what I
recall -- it's been a while since I used the DB API).
> The use case isn't odd or confused or oxymoronic --
> it's very natural. The problem is that the natural and common use case
> doesn't translate into nice Python when you use iterators.
There's no reason why the *specific* iterator returned by a query
can't have an additional API to inquire whether it returned any
results at all, or an exact result count; IIRC next() is but one of
the many methods of query results.
But this doesn't generalize to a flaw in the iterator protocol per se.
--
--Guido van Rossum (home page: http://www.python.org/~guido/)
More information about the Python-3000
mailing list