PEP 255: Simple Generators, Revised Posting

Rainer Deyke root at rainerdeyke.com
Sun Jun 24 19:58:14 EDT 2001


"Bernhard Herzog" <bh at intevation.de> wrote in message
news:m3k821snlr.fsf at intevation.de...
> Being able to easily write a function that does nothing (in fact it's
> the most trivial function one can write) is very useful in practice, so
> as a generalization being able to write empty generators might be
> useful, too. I'm not sure about that, though, because I don't have
> enough experience with them.

Of course it is.  Consider:

class Head:
  pass

class Lion:
  def __init__(self):
    self.head = Head()
  def iter_heads(self, filter_fun):
    if filter_fun(self.head):
      yield self.head

class Hydra:
  def __init__(self):
    self.heads = [Head() for i in range(7)]
  def iter_heads(self, filter_fun):
    for head in self.heads:
      if filter_fun(head):
        yield head

class Slime:
  def __init__(self):
    pass
  def iter_heads(self, filter_fun):
    return
    yield None # This is a null generator

Note that I *could* have simply returned 'iter([])' from 'Slime.iter_heads'
for almost the same effect.  I chose not to do this because consistency is a
Good Thing.  Now consider this:

class Lion:
  def __init__(self):
    self.head = Head()
  def iter_heads(self, filter_fun):
    print 'Started iterating lion heads.'
    if filter_fun(self.head):
      yield self.head
    print 'Finished iterating lion heads.'

class Hydra:
  def __init__(self):
    self.heads = [Head() for i in range(7)]
  def iter_heads(self, filter_fun):
    print 'Started iterating hydra heads.'
    for head in self.heads:
      if filter_fun(head):
        yield head
    print 'Finished iterating hydra heads.'

class Slime:
  def __init__(self):
    pass
  def iter_heads(self, filter_fun):
    print 'Started iterating slime heads.'
    print 'Finished iterating slime heads.'
    return
    yield None # This is a null generator

In this case, the non-generator 'Slime.iter_heads' would be long and messy.
I'm almost certain that the non-empty non-yielding generator will become a
common idiom.


--
Rainer Deyke (root at rainerdeyke.com)
Shareware computer games           -           http://rainerdeyke.com
"In ihren Reihen zu stehen heisst unter Feinden zu kaempfen" - Abigor





More information about the Python-list mailing list