A simple generator application

Avery Andrews andrews at pcug.org.au
Sun Oct 13 00:55:26 CEST 2002

On Sat, 12 Oct 2002, Doug Fort wrote:

> I'm interested in generators. I've read Dr. David Mertz's 'Charming
> Python' articles (http://gnosis.cx/publish/tech_index_cp.html), and 
> the discussion here on c.l.p. 
> I've been looking for an excuse to actually use a generator. I need to put
> include guards on a bunch of C++ header files. So I started out to create
> a generator that does what os.path.walk does, with yield in place of the
> callback 'visitor' function.

Here's one that I just wrote that actually does something, basically
combining two calls to an interface to AmziProlog into one convenient
package, the context is looking at sequentially numbered lines of text
where some line numbers appear twice (variants, errors, etc),
'next_line_num' is a 'deterministic' Prolog call that produces one answer,
'retrive_num_line' is a 'nondeterminstic one that produces multiple
answers.  the results of the .run and .calls methods are basically
copies of the argument with the capital letters filled out by whatever
the Prolog engine can come up with, if anything, that makes the statements
true; the argument-positions are then accessible by indexing:

  # generator to smooth out call-redo cycle.  Might be better
  #  if the Prolog were also rethought.
  def LineGetter(engine, linenum=0):
      # Loops indefinitely until it kills itself
      while (1):
          if lino == None:
          linenum = int(lino[2])
          for result in engine.calls("retrieve_num_line(%d,T,I,N,L)"%linenum):
              yield result[1:6]

More information about the Python-list mailing list