empty lists vs empty generators

jfj jfj at freemail.gr
Mon May 2 20:02:58 EDT 2005


Brian Roberts wrote:

> 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.
>

Usually it will be the job of the generator to signal something like 
this.  I think a possible way might be:

     class GeneratorEmpty: pass

     def generator():
          if not X:
              raise GeneratorEmpty
          for i in X:
               yield i

     try:
          for x in generator
              something (x)
     except GeneratorEmpty:
          generator_special_case

The trick is that when generators raise exceptions they terminate.
Although this is probably not what you want.  The thing is that you
cannot know if a generator will return any elements until you call
its next() method.


> Q2: Is there a way that handles both lists and generators, so I don't
> have to worry about which one I've got?

I don't think this is possible.  A generator must be called (with
next()) in order for its code to take over and see if it is empty or
not.  Unlike the list.


jfj




More information about the Python-list mailing list