Functional/Best?

Terry Reedy tjreedy at udel.edu
Sun Jul 13 14:00:32 EDT 2008



Tim Cook wrote:
> I guess I can classify my application(s) as more procedural than
> anything else.  But I have a question about the best way to handle
> something in Python.
> 
> When given a mapping of keywords, I want to call a function based on a
> certain keyword found when parsing a text file.  The mapping looks like
> this:
> 
> definClassMap={'SECTION':'bldSection','COMPOSITION':'bldComposition','OBSERVATION':'bldObservation','ITEM_TREE':'bldItemTree'}
> 
> So if the text file contains 'ITEM_TREE'  I want to call bldItemTree
> which creates an instance of the class ItemTree.  
> 
> I currently use an if ..., elif ... construct.
> Is there a better, more efficient, more Pythonic way of doing this?

Yes. Create a mapping of keywords to function objects rather than to 
function names!

def bldSection(): <whatever>
...
def bldItemTree(): <whatever else>

class_map={
   'SECTION':bldSection,
   'COMPOSITION':bldComposition,
   'OBSERVATION':bldObservation,
   'ITEM_TREE':bldItemTree, # trailing comma allows easy additions
}

for word in parselist:
   try;
     class_map[word]()
   except KeyError:
     <whatever for non-keys>

tjr





More information about the Python-list mailing list