On Thu, Sep 27, 2007 at 01:33:47PM +1200, Greg Ewing wrote:
Oleg Broytmann wrote:
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. 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.
In most cases the code in those libraries is, using the word of Mr. van Rossum, "archaic". It was developed for old versions of Python (long before Python has got the iterator protocol). I will file bug reports and patches (I have filed one about logginig/__init__.py) to allow developers to either fix the code or document the fact the code really requires a finite sequence. Unfortunately now when my code no longer raises an exception it would be harder to spot the buggy libraries.
Generally I think it's a bad idea to try to protect people from themselves when doing so can interfere with legitimate usage.
I agree. I admitted in mailing list it was my design mistake. The offending __nonzero__ was removed from SVN today.