matching keyword arguments to specific methods

Laura Creighton lac at strakt.com
Mon Jan 27 22:11:43 EST 2003


> 
> "Paul Rubin" <phr-n2003b at NOSPAMnightsong.com> wrote:
> > I don't quite understand your example but I think you want something like:
> >
> >     if hasattr(self, key):
> >        getattr(self,key)(whatever)
> 
> Yes, that works perfectly. Thanks.
> Donnal Walter

This has one potential problem:  If your function has a data attribute,
it will try to run it.  By this I mean:

self.number=42 

hasattr(self, 'number') is true.

You may want to check:

method = getattr(self, method_name, None) # return None if doesn't exit
if callable(method):
   method(*args, **kwargs)

Laura Creighton





More information about the Python-list mailing list