apply()?

Fredrik Lundh fredrik at pythonware.com
Tue Dec 6 00:57:51 CET 2005


Ron Griswold wrote:

> I'm almost positive I've seen a function somewhere that will call a
> method of an object given the method's name. Something like:
>
> apply(obj, "func_name", args)
>
> is equivalent to:
>
> obj.func_name(args)
>
> For some reason I thought this was the apply function, but that doesn't
> appear to be the case. Can someone point me in the right direction?

sounds like you're looking for getattr (get attribute):

    func = getattr(obj, "func_name")
    result = func(args)

or, in one line:

    result = getattr(obj, "func_name")(args)

a common pattern is

    try:
        func = getattr(obj, "func_name")
    except AttributeError:
        ... deal with missing method ...
    else:
        result = func(args)

(this makes sure that an AttributeError raise inside the method isn't
confused with an AttributeError raise by getattr).

another pattern is

    func = getattr(obj, "func_name", None)
    if func:
        func(args)

which only calls the method if it exists.  here's a variation:

    func = getattr(obj, "func_name", None)
    if callable(func):
        func(args)

hope this helps!

</F>






More information about the Python-list mailing list