SAX questions...

Andrew Dalke adalke at mindspring.com
Tue Jul 22 18:18:32 EDT 2003


Timothy Grant:
> def startElement(self, name, attr):
>     if name == "foo":
>        do_foo_stuff()
>     elif name == "bar":
>         do_bar_stuff()
>     elif name == "baz":
>         do_baz_stuff()
  ...
> I could create a dictionary and dispatch to the correct method based on a
> dictionary key. But it seems to me there must be a better way.

  def startElement(self, name, attr):
    f = getattr(self, "do_" + name + "_stuff", None)
    if f is not None:
      f()

However, the dictionary interface is probably faster, and you can
build it up using introspection, like

class MyHandler:
    def __init__(self):
        self.start_d = {}
        self.end_d = {}
        for name in MyHandler.__dict__:
          if name.startswith("do_") and name.endswith("_stuff"):
            s = name[3:-6]
            self.start_d[s] = getattr(self, name)
         elif name.startswith("done_") and ...
            s = name[5:-6]
            self.end_d[s] = getattr(self, name)

    def startElement(self, name, attrs):
      f = self.start_d.get(name)
      if f:
        f()

    ...

                    Andrew
                    dalke at dalkescientific.com






More information about the Python-list mailing list