empty lists vs empty generators
Terry Reedy
tjreedy at udel.edu
Tue May 3 02:35:05 EDT 2005
"Brian Roberts" <brian at mirror.org> wrote in message
news:509534af.0505021514.5e49aa2 at posting.google.com...
> I'm using using generators and iterators more and more intead of
> passing lists around, and prefer them. However, I'm not clear on the
> best way to detect an empty generator (one that will return no items)
> when some sort of special case handling is required.
If you write an iterator class instead of the abbreviated generator form,
and you can tell from the initialization parameters whether there will be
any data, then you can give the class a __nonzero__ method. You can also
have an initially nonempty iterator flag when it becomes empty.
My point is that writing an iterator as a generator is a convenience, not a
necessity, and that one gives up the full flexibility of an iterator class
when one does so, but that one is not required to do so.
I quite understanding wanting to have your cake and eat it too. The
convenience is sometimes major.
Terry J. Reedy
More information about the Python-list
mailing list