bool evaluations of generators vs lists

Terry Reedy tjreedy at udel.edu
Tue Feb 10 17:29:23 EST 2009


Josh Dukes wrote:

> 
> I was actually aware of that (thank you, though, for trying to help).
> What I was not clear on was if the boolean evaluation is a method of an
> object that can be modified via operatior overloading (in the same way
> + is actually .__add__()) or not. Clearly __nonzero__ is the operator I
> was curious about. Thanks for that info. 

.__bool__ in 3.0.


> The thing I don't understand is why a generator that has no iterable
> values is different from an empty list. Why shouldn't bool ==
> has_value?? Technically a list, a tuple, and a string are also objects
> but if they lack values they're evaluated as False. It seems to me that
> a generator is an object that intends to replace lists where lazy
> evaluation would be more efficent. Here is one place where that's
> definitely true. 

Generator functions are abbreviated iterator classes.  If you want 
iterators with more functionality, write an iterator class.  In 
particular, you can add a .__bool__ method for empty or not or even a 
.__len__ method if you can accurately calculate the number of items 
remaining.

> The main reason I'm interested in this is that it improves performance
> immensely over boolean evaluation of large lists (as the attached code
> shows). It seems to me if I could use find a good use for it in my
> experimentation that someone else might also want to do the same thing
> in real-world code. 

Terry Jan Reedy




More information about the Python-list mailing list