[Python-3000] Iterators for dict keys, values, and items == annoying :)
Guido van Rossum
guido at python.org
Fri Mar 24 16:13:55 CET 2006
On 3/24/06, Greg Ewing <greg.ewing at canterbury.ac.nz> wrote:
> > Someone else wrote:
> > > When I was just
> > > first learning Python I thought this would work:
> > >
> > > for item in select_results:
> > > ...
> > > else:
> > > ... stuff when there are no items ...
> > >
> > > But it doesn't work like that.
>
> I have to agree that's actually a more intuitive use
> of "else" in relation to a for-loop. It's a pity that
> some other word wasn't chosen that would have left
> "else" free for this purpose.
>
> Could something perhaps be done about this in Py3k?
> Blatantly changing the meaning of "else" here might
> be going too far, but maybe some other construct could
> be found that expresses the same intent.
I suspect that this isn't good enough for the crowd who want to
special-case "empty", and in fact the "empty flag" pattern won't work
for them as well. They typically want to do this:
results = query()
if not results:
print "<h1>No results</h1>"
else:
print "<h1>Results</h1>"
print "<table>"
for value in results:
print "<tr><td>%s</td></tr>" % value
print "</table>"
IOW they want to do something *before* entering the for-loop only if
it's not empty.
In this type of use case, casting to list() is totally fine -- if the
list contains more than a few dozen items they'd want to insert
pagination code anyway...
--
--Guido van Rossum (home page: http://www.python.org/~guido/)
More information about the Python-3000
mailing list