Kent Johnson wrote:
Another way to do this is to use dispatch methods. If you have extra processing to do for each tag, this might be a good way to go.

I'm going to assume that your data lines have the form 'tag=data'. Then your Node class might have methods that look like this:

class Node:
  ...
  def parse_metadata(self, line):
    tag, data = line.split('=', 1)
    try:
      handler = getattr(self, 'handle_' + tag)
    except AttributeError:
      print 'Unexpected tag:', tag, data
    else:
      handler(data)

  def handle_something_tag(self, data):
    self.something = int(data) # for example

  def handle_last(self, data):
    try:
      self.another_thing.append(data) # attribute is a list
    except AttributeError:
      self.another_thing = [data]

and so on. This organization avoids any if / else chain and puts all the processing for each tag in a single place.

One more idea. If you have 20 different tags but only four different ways of processing them, maybe you want to use a dict that maps from the tag name to a tuple of (attribute name, processing method). With this approach you need only four handler methods instead of 20. It would look like this:


metadata_dict = {
  'something_tag' : ( 'something', self.handle_int ),
  'last' : ( 'another_thing', self.handle_list ),
}

def parse_metadata(self, line):
  tag, data = line.split('=', 1)
  try:
    attr_name, handler = metadata_dict[tag]
  except AttributeError:
    print 'Unexpected tag:', tag, data
  else:
    handler(attr_name, data)

def handle_int(self, attr_name, data):
  setattr(self, attr_name, int(data))

def handle_list(self, attr_name, data):
  l = getattr(self, attr_name, [])
  l.append(data)
  setattr(self, attr_name, l)

I-have-to-stop-replying-to-my-own-posts-ly yours,
Kent

_______________________________________________
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor

Reply via email to