Oleg Broytmann wrote:
(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.