apply()?

Ron Griswold RGriswold at Rioting.com
Mon Dec 5 19:41:55 EST 2005


Just the ticket. Thank you!

Ron Griswold
Character TD
R!OT Pictures
rgriswold at rioting.com


-----Original Message-----
From: python-list-bounces+rgriswold=rioting.com at python.org
[mailto:python-list-bounces+rgriswold=rioting.com at python.org] On Behalf
Of Fredrik Lundh
Sent: Monday, December 05, 2005 3:58 PM
To: python-list at python.org
Subject: Re: apply()?

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>



-- 
http://mail.python.org/mailman/listinfo/python-list




More information about the Python-list mailing list