[Python-Dev] Iterating over objects of unknown length
Guido van Rossum
guido at python.org
Wed Sep 26 18:29:10 CEST 2007
The logging code looks archaic: IMO it should be:
if args and len(args) == 1 and isinstance(args, dict) and args:
But I also fail to see why you would be so draconian as to disallow
truth testing of a query altogether. Your query looks like an
iterator. There are tons of other iterators in the language, library
and 3rd party code, and it would be madness to try to fix all of them
in the way you suggest just because some users don't get the concept
So I'm for #1 *and* #2.
On 9/26/07, Oleg Broytmann <phd at phd.pp.ru> 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. As an SQL query doesn't know in advance if it will
> produce any row the class doesn't implement __len__(). Moreover, users of
> the class sometimes write
> if sqlQuery:
> for row in sqlQuery: ...
> # no rows
> which is a bug (the query doesn't know if it's True or False; to find it
> out the user have to execute the query by trying to iterate over it). To
> prevent users from writing such code the class implements __nonzero__()
> that always raises an exception.
> Unfortunately, I found some libraries test the object in boolean context
> before iterating over it and that, of course, triggers the exception from
> Even worse, some libraries test the object in boolean context regardless
> of iterating over it. For example, logging module (this is where my
> question becomes "developing for Python") triggers the exception in such
> simple case:
> logginig.debug("Query: %s", sqlQuery)
> Funny, the code
> logginig.debug("Query: %s, another: %s", sqlQuery, another_value)
> doesn't trigger the exception. This is due to the code in
> if args and (len(args) == 1) and args and (type(args) == types.DictType):
> args = args
> (class LogRecord, method __init__). "and args" triggers the exception.
> My questions are:
> 1. Should I consider this a bug in the logging module (and other libraries)
> and submit patches?
> 2. Or should I stop raising exceptions in __nonzero__()?
> In this particular case with logging the fix is simple - do "and args"
> after type check.
> Oleg Broytmann http://phd.pp.ru/ phd at phd.pp.ru
> Programmers don't die, they just GOSUB without RETURN.
> Python-Dev mailing list
> Python-Dev at python.org
> Unsubscribe: http://mail.python.org/mailman/options/python-dev/guido%40python.org
--Guido van Rossum (home page: http://www.python.org/~guido/)
More information about the Python-Dev