[Tutor] Function return

Kirby Urner urnerk@qwest.net
Wed, 20 Feb 2002 20:24:46 -0800

 >  closed = closedRecords("closed.001", "LIS00139")
 >  print 'No records', closed.noRecords()
 >  recs = closed.getRecords

Here's a problem:  by leaving off the open-close parentheses,
you return a reference to the function, instead of causing
the function to execute.  Which explains...

 >  print "Records:",recs  # Prints out what looks like addresses
                            to the function, not the array

...why recs is a reference to a method in your class.

 >  for r in recs:               # Fails with not a sequence error
 >    print r["jobcode"]

Just put the parentheses after closed.getRecords() <-- like this
and it'll probably work.

A comment on style:  I think using a class to wrap the the
functionality needed to read some fixed length records is overkill
in this example.  What you get at the end of the day is a single
instance containing a list of dictionary instances, which is
a somewhat exotic data structure.

I think a more "normal" implementation of this idea would be to
have a dictionary of objects when done, with each object
corresponding to a record in the original file.  An object is
*like* a dictionary, and could have properties like jobname
or whatever corresponds to the fields in your DBF.

In pseudocode:

   myrecords = {}

   class Record:
      def __init__(self, jobname, other1, other2....):
          # or you could pass a dictionary as an arg
          self.jobname = jobname
          self.other1 = other1
          self.other2 = other2

   def createRecords(filename):
       global myrecords
       f = open(filename)
       lines = f.readlines()
       for line in lines:
           values = parseLine(line)
           # here we presume values[0] is unique
           myrecords[values[0]] = Record(values)

But even this might be overkill.  It all depends on what you're
planning to do with all this data.


PS:  for posting to tutor, best to post in plaintext only.
You had some proportional font going, which makes it harder
to read the code (some people say we should get used to
coding in proportional types, but that's advice I think
most programmers thankfully ignore).