Boolean tests [was Re: Attack a sacred Python Cow]
mattheww at chiark.greenend.org.uk
Wed Jul 30 21:55:03 CEST 2008
Terry Reedy <tjreedy at udel.edu> wrote:
>Carl Banks wrote:
>> That's not what I was asking for. I was asking for a use case for "if
>> x" that can't be replaced by a simple explicit test. Your example
>> didn't satisfy that.
> But I believe my example of an iterator with __bool__ but not with
> __len__ does.
On the other hand, iterators provide a clear example of problems with "if x":
__nonzero__ for iterators (in general) returns True even if they are 'empty'.
For example, this function (which attempts to avoid making an expensive
call when not necessary) is buggy, but easy to write if you've been
taught that "if x" will work with any kind of object.
def frob(widgets, power):
frobber = Frobber(power) # expensive call
for widget in widgets:
More information about the Python-list