Main Content

Catching the fishes first?

Archive - Originally posted on "The Horse's Mouth" - 2011-09-27 23:45:16 - Graham Ellis

If you make a fish pie for your friends, you'll catch all the fish you need before you start the preparation and cooking work, and you'll do the cooking all at once.

If you run a fish pie factory, you'll have a steady flow of fish arriving while your production line is running. Receiving all the fish you need before you start production each week would give you a major storage problem (inside) or an issue with some rathe keen gulls (outside).

In Python, you can iterate through a list - and that's fine for the smaller cases. But in cases where you have a substantial amount of data, you should read / request / work it out on a "just in time" basis, using a generator function.

Here's an example piece of code to show you how ...

  # Getting all the fish at once
  
  def getvals(top):
  stuff = []
    vat = 0
    while vat < top:
      print "caught mackrel no",vat
      stuff.append(vat)
      vat += 1
    return stuff
  
  # Just in time
  
  def xgetvals(top):
    vat = 0
    while vat < top:
      print "caught mackrel no",vat
      yield vat
      vat += 1
  
  ending = 15
  
  for value in getvals(ending):
    print "Added to pie",value
  
  for value in xgetvals(ending):
    print "Added to pie",value