Calling class method by name passed in variable
Nick Craig-Wood
nick at craig-wood.com
Fri May 23 09:30:08 EDT 2008
Bruno Desthuilliers <bruno.42.desthuilliers at websiteburo.invalid> wrote:
> Nick Craig-Wood a ?crit :
> > Bruno Desthuilliers <bruno.42.desthuilliers at websiteburo.invalid> wrote:
> >>> Can someone suggest an efficient way of calling method whose name is
> >>> passed in a variable?
> >>>
> >> method = getattr(obj, 'method_name', None)
> >> if callable(method):
> >> method(args)
> >
> > I think that that is needless LBYL...
>
> From experience, it isn't.
> > getattr(obj, 'method_name')(args)
> >
> > Will produce some perfectly good exceptions
>
> The problem is that you can't tell (without reading the exception's
> message and traceback etc) if the exception happened in you code or
> within the called method.
I guess it depends on whether you are expecting it to ever fail or
not. If a user types in method_name then yes you are right checking
stuff and producing a nice error is good. However if it is part of
your internal program flow and you never expect it to go wrong in
normal operation then I'd be quite happy with the exception and
backtrace to debug the problem.
--
Nick Craig-Wood <nick at craig-wood.com> -- http://www.craig-wood.com/nick
More information about the Python-list
mailing list