[Python-Dev] Iterating over objects of unknown length
Greg Ewing
greg.ewing at canterbury.ac.nz
Thu Sep 27 03:33:47 CEST 2007
Oleg Broytmann wrote:
> Hello!
>
> (This seems like a "developing with Python" question and partially it is
> but please read on.)
>
> I have a class that represents SQL queries. Instances of the class can
> be iterated over. ... users of
> the class sometimes write
>
> if sqlQuery:
> for row in sqlQuery: ...
> else:
> # no rows
>
> To prevent users from writing such code the class implements __nonzero__()
> that always raises an exception.
I'm not sure I like that idea. It's common practice to write
'if x:' as a shorthand for 'if x is not None:' when it's known
that x is an object that doesn't have a notion of emptiness.
A __nonzero__ that always raises an exception just to spite
you interferes with that.
Another thing is that any code doing "if x" to test for
emptiness is clearly expecting x to be a sequence, *not*
an iterator, and you've violated the contract by passing
it one. This is what you may be running into with the libraries
you mention.
Generally I think it's a bad idea to try to protect people
from themselves when doing so can interfere with legitimate
usage.
--
Greg Ewing, Computer Science Dept, +--------------------------------------+
University of Canterbury, | Carpe post meridiem! |
Christchurch, New Zealand | (I'm not a morning person.) |
greg.ewing at canterbury.ac.nz +--------------------------------------+
More information about the Python-Dev
mailing list