SAX questions...

Bob Gailer bgailer at alum.rpi.edu
Tue Jul 22 14:02:45 EDT 2003


At 10:22 AM 7/22/2003 -0700, Timothy Grant wrote:

>I've worked with DOM before, but never SAX, I have a script that seems to 
>work
>quite well, but every time I look at it I think it's amazingly unweildly and
>that I must be doing something wrong.
>
>def startElement(self, name, attr):
>     if name == "foo":
>         do_foo_stuff()
>     elif name == "bar":
>         do_bar_stuff()
>     elif name == "baz":
>         do_baz_stuff()
>
>There's similar code in endElement() and characters() and of course, the more
>tags that need processing the more unweildly each method becomes.
>
>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.

Please note that this is not a SAX-specific question. I suggest a subject 
of How To Manage Function Dispatching.

Your question comes down to what's the "best" way to dispatch a piece of 
logic based on some condition. You have already given 2 good alternatives: 
your example, and using a dictionary. The other approach I sometimes use is 
defining a class for each condition and then instantiating the class as needed.

Class foo:
   def __init__(self):
     # do foo stuff

etc for each case, then

try: x = eval(name+'()')
except: raise "Unknown name " + name

Which, of course, is just a dictionary lookup in disguise.

Bob Gailer
bgailer at alum.rpi.edu
303 442 2625
-------------- next part --------------

---
Outgoing mail is certified Virus Free.
Checked by AVG anti-virus system (http://www.grisoft.com).
Version: 6.0.500 / Virus Database: 298 - Release Date: 7/10/2003


More information about the Python-list mailing list