Calling a function dynamically

Peter Otten __peter__ at web.de
Thu Jan 8 11:51:01 EST 2004


Paradox wrote:

> I would like to call a function whose name I supply at runtime.
> Something like this but it didn't work
> 
> functionName = 'run'
> instance = ClassDef()
> args = [1, 2]
> 
> #want the dynamic equivalant of
> #instance.run(*args)
> 
> #This didn't work cause there was no __call__ attribute. Why?
> value = instance.__call__[functionName](*args)

The __call__() method is implicitly invoked when you write

value = instance(some, args)

Here's a way to abuse the [] operator (implemented by __getitem__()) to
dynamically select a method:

>>> class Test:
...     def __getitem__(self, name):
...             return getattr(self, name)
...     def run(self, *args):
...             print "run%s" % (args,)
...
>>> t = Test()
>>> t["run"]
<bound method Test.run of <__main__.Test instance at 0x40295b0c>>

"bound method" means that both instance and method are stored, so that
for the actual call you need not provide an explicit self parameter:

>>> t["run"]("alpha", "beta", "gamma")
run('alpha', 'beta', 'gamma')


Peter




More information about the Python-list mailing list