Boolean value of generators

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Thu Oct 14 22:21:54 EDT 2010


On Thu, 14 Oct 2010 14:43:29 -0400, Albert Hopkins wrote:


> There may be times, however, that a generator may "know" that it
> doesn't/isn't/won't generate any values, and so you may be able to
> override boolean evaluation.  Consider this example:
[snip example]


This is a good example, but it's not a generator, it's an iterator :)

The two are similar in that they both produce values lazily, as required, 
but generators are a special case of iterators: generators are a special 
form of the function syntax which returns a lightweight and simple 
iterator. Iterators are more general. They're an interface rather than a 
type, so any class you build which matches the iterator protocol is an 
iterator, but only a function with a yield is a generator. 

Other than this nit-pic, your idea of making a custom iterator with a 
__nonzero__ method is an excellent idea.


-- 
Steven



More information about the Python-list mailing list