matching keyword arguments to specific methods

Laura Creighton lac at strakt.com
Tue Jan 28 04:11:43 CET 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