how to repeat function definitions less

MRAB google at
Sun Mar 15 16:51:38 CET 2009

alex goretoy wrote:
> I would imagine that I could do this with a generator and setattr, but I 
> am still learning how to do that kinda of coding....maybe if I had a 
> dictionary like this and then loaded it
> d={
>     "site_name":["s","site",'sites','site_name','site_names'],
>     "jar_name":["j","jar",'jars','jar_name','jar_names'],
>     ...
> }
Instead of:

     if _args[0] in ("s","site",'sites'):

you could use a dict where the key is _args[0] and the value is the method:

     handlers = {"s": self.site_name, "site": self.site_name, ...}
     except KeyError:
         # Unknown option

The 'handlers' dict could be built from your 'd' dict above.

More information about the Python-list mailing list