Creating different classes dynamically?

Victor Hooi victorhooi at
Mon Dec 10 01:35:26 CET 2012


I have a directory tree with various XML configuration files.

I then have separate classes for each type, which all inherit from a base. E.g.

    class AnimalConfigurationParser:

    class DogConfigurationParser(AnimalConfigurationParser):

    class CatConfigurationParser(AnimalConfigurationParser):

I can identify the type of configuration file from the root XML tag.

I'd like to walk through the directory tree, and create different objects based on the type of configuration file:

    for root, dirs, files in os.walk('./'):
        for file in files:
            if file.startswith('ml') and file.endswith('.xml') and 'entity' not in file:
                with open(os.path.join(root, file), 'r') as f:
                        tree = etree.parse(f)
                        root = tree.getroot()
                        # Do something to create the appropriate type of parser
                    except xml.parsers.expat.ExpatError as e:
                        print('Unable to parse file {0} - {1}'.format(, e.message))

I have a dict with the root tags - I was thinking of mapping these directly to the functions - however, I'm not sure if that's the right way to do it? Is there a more Pythonic way of doing this?

    root_tags = {
                   'DogRootTag': DogConfigurationParser(),
                    'CatRootTag': CatConfigurationParser(),


More information about the Python-list mailing list