Calling class method by name passed in variable

Nick Craig-Wood nick at craig-wood.com
Fri May 23 05:30:09 EDT 2008


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...

   getattr(obj, 'method_name')(args)

Will produce some perfectly good exceptions

    >>> class A(object):
    ...     def __init__(self):
    ...             self.x = 2
    ...     def f(self, x):
    ...             print x == self.x
    ...
    >>> obj = A()
    >>> getattr(obj, 'floop')(1)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    AttributeError: 'A' object has no attribute 'floop'
    >>> getattr(obj, 'x')(1)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: 'int' object is not callable
    >>> getattr(obj, 'f')(1)
    False
    >>>

-- 
Nick Craig-Wood <nick at craig-wood.com> -- http://www.craig-wood.com/nick



More information about the Python-list mailing list