473,385 Members | 1,470 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,385 software developers and data experts.

Calling a function dynamically

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)


Thanks Joey
Jul 18 '05 #1
5 3431
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 "function" is in fact a method on the instance, that is handled like a
regular attribute. So using getattr should do what you want:

value = getattr(instance, functionName)(*args)

__call__ is for a completely different purpose, which is to define instances
that behave like functions:
class Spammer: .... def __call__(self):
.... print 'spam'
.... o = Spammer()
o()

spam
HTH
--
- Eric Brunel <eric dot brunel at pragmadev dot com> -
PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com

Jul 18 '05 #2
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)


Thanks Joey


This should work:
getattr(instance, functionName)(*args)

regards,
anton.
Jul 18 '05 #3
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

Jul 18 '05 #4
In article <bt*************@news.t-online.com>, Peter Otten wrote:
Paradox wrote:
I would like to call a function whose name I supply at runtime.
[snip]


Here's a way to abuse the [] operator (implemented by __getitem__()) to
dynamically select a method...
t["run"]("alpha", "beta", "gamma")

run('alpha', 'beta', 'gamma')


I wouldn't necessarily consider this abuse. This behavior (where
square-bracket- and dot-syntax are functionally equivalent) is the normal
behavior of JavaScript, and it makes dynamic lookup of method names a snap.
Python is more flexible in giving you the option to have separate namespaces
for items and attributes, but if it makes more sense for an object to merge
the two, I see nothing wrong with it.

--
..:[ dave benjamin (ramenboy) -:- www.ramenfest.com -:- www.3dex.com ]:.
: d r i n k i n g l i f e o u t o f t h e c o n t a i n e r :
Jul 18 '05 #5
Thanks to all. The getattr was exactly what I need and the __getitem__
override is a nice touch.
Dave Benjamin <ra***@lackingtalent.com> wrote in message news:<slrnbvr5hb.seu.ra***@lackingtalent.com>...
In article <bt*************@news.t-online.com>, Peter Otten wrote:
Paradox wrote:
I would like to call a function whose name I supply at runtime.
[snip]


Here's a way to abuse the [] operator (implemented by __getitem__()) to
dynamically select a method...
> t["run"]("alpha", "beta", "gamma")

run('alpha', 'beta', 'gamma')


I wouldn't necessarily consider this abuse. This behavior (where
square-bracket- and dot-syntax are functionally equivalent) is the normal
behavior of JavaScript, and it makes dynamic lookup of method names a snap.
Python is more flexible in giving you the option to have separate namespaces
for items and attributes, but if it makes more sense for an object to merge
the two, I see nothing wrong with it.

Jul 18 '05 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
by: jarmopy | last post by:
Hi, I have made a service with C# and calling that service class from another C# program with remoting. (Referendes from the calling program) That service class is configured so that garpage...
4
by: Jerry Krinock | last post by:
I've written the following demo to help me understand a problem I'm having in a larger program. The "main" function constructs a Foo object, and then later "reconstructs" it by calling the...
2
by: Joe | last post by:
I have 3 functions: ClientInfoA is doing something ClientInfoB is doing something SelectFunction2Run is a function to determine which function needed to run based on the value of the variable...
5
by: Francesco Bochicchio | last post by:
Hi all, anybody knows if there is a (standard, portable) way to dinamically build a list of parameters to call a C function? Something like va_start & co, but to be used on the calling side? ...
5
by: Simon Harris | last post by:
Hi All, I am trying to call a method in a web form, from an event fired in a user control. My user control displays a map, which has a link button to enlarge/shrink the map. When the user...
35
by: Michel Sanner | last post by:
Hello, One of the greatest feature of Python in my opinion is the way the interpreter can be used to integrate a wide variety of software packages by dynamically linking them. This approach has...
3
by: hardieca | last post by:
My apologies if this gets posted twice... I am trying to determine whether or not a class has a function, and if it does, build a reference to it dynamically which I can then use to access the...
5
by: sfeher | last post by:
Hi, Is there a way to know when a function is available for me to call it from a dynamically loaded a javascript? I use this code to load the include.js file and then I call testIncludeFn()...
15
by: =?Utf-8?B?VG9tIENvcmNvcmFu?= | last post by:
I've been led to believe by several articles, particularly Eric Gunnerson's C# Calling Code Dynamically, that calling a method dynamically through Reflection was much slower than through a...
6
by: Ole Nielsby | last post by:
VC has a __cdecl specifier which allows functions and methods to be called with varying parameter count. (I understand this is the default for functions in general but in VC, instances use...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.