dynamic invoke

Diez B. Roggisch deets at nospam.web.de
Fri Oct 19 07:19:54 EDT 2007


 lukasz.f24 at gmail.com wrote:

> On 19 Oct, 11:45, Jarek Zgoda <jzg... at o2.usun.pl> wrote:
>> lukasz.... at gmail.com napisa³(a):
>>
>> > Is there any way (other then eval) to invoke a method by passing
>> > method name in a string.
>> > It's very simple in php:
>> > $oFoo = new Foo();
>> > $dynamiMethod = "bar";
>> > $oFoo->$dynamiMethod();
>>
>> > Unfortunately I can't find a good solution to do the same thing in
>> > python. Does it have some build-in function to do it?
>>
>> foo = getattr(module_or_object, 'function_name')
>> foo()
>>
>> --
>> Jarek Zgoda
>> Skype: jzgoda | GTalk: zg... at jabber.aster.pl | voice: +48228430101
>>
>> "We read Knuth so you don't have to." (Tim Peters)
> 
> Superb!
> I was lookig for something like this. Belive me or not but i spent
> lots of time looking for this simple solution :)

The above clearly is a solution to your problem. I just wonder if you _need_
it. PHP doesn't have the concept of a function reference. So you need to
store/use names.

But in Python you can do this:

def foo():
    print "foo"

callback = foo
callback()

As trivial this code is, it illustrates one thing: passing around functions
is as easy as passing around other values. So maybe you don't need a
function name. Only a suggestion to ponder about though, it might be that
your usecase is not suited for the above.

Diez



More information about the Python-list mailing list