tags:

views:

403

answers:

3

Hi all!
I'm writing a parser for an internal xml-based metadata format in python. I need to provide different classes for handling different tags. There will be a need for a rather big collection of handlers, so I've envisioned it as a simple plugin system. What I want to do is simply load every class in a package, and register it with my parser. My current attempt looks like this:
(Handlers is the package containing the handlers, each handler has a static member tags, which is a tuple of strings)

class MetadataParser:
    def __init__(self):
        #...
        self.handlers={}
        self.currentHandler=None
        for handler in dir(Handlers): # Make a list of all symbols exported by Handlers
            if handler[-7:] == 'Handler': # and for each of those ending in "Handler"
                handlerMod=my_import('MetadataLoader.Handlers.' + handler)
                self.registerHandler(handlerMod, handlerMod.tags) # register them for their tags

    # ...

    def registerHandler(self, handler, tags):
        """ Register a handler class for each xml tag in a given list of tags """
        if not isSequenceType(tags): 
            tags=(tags,) # Sanity check, make sure the tag-list is indeed a list
        for tag in tags:
            self.handlers[tag]=handler

However, this does not work. I get the error AttributeError: 'module' object has no attribute 'tags' What am I doing wrong?

A: 

Probably one of your handlerMod modules does not contain any tags variable.

sth
A: 

I suggest you read the example and explanation on this page where how to write a plug-in architecture is explained.

Sushant
A: 

First off, apologies for poorly formated/incorrect code.
Also thanks for looking at it. However, the culprit was, as so often, between the chair and the keyboard. I confused myself by having classes and modules of the same name. The result of my_import (which I now realize I didn't even mention where it comes from... It's from SO: link) is a module named for instance areaHandler. I want the class, also named areaHandler. So I merely had to pick out the class by eval('Handlers.' + handler + '.' + handler).
Again, thanks for your time, and sorry about the bandwidth

carlpett