473,804 Members | 3,030 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 3455
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(instanc e, 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(instanc e, 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__(sel f, name):
.... return getattr(self, name)
.... def run(self, *args):
.... print "run%s" % (args,)
.... t = Test()
t["run"] <bound method Test.run of <__main__.Tes t 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***@lackingt alent.com> wrote in message news:<slrnbvr5h b.seu.ra***@lac kingtalent.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
2433
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 collection is not used in this class. (singleton class + override InitializeLifetimeService ) The service class uses C++ unmanaged function from dll (using DLLimport).
4
7293
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 constructor again. In my larger program, I find that the member variables don't get re-initialized when "reconstructed". I don't have that problem in this demo, but the second time the constructor is called, its "this" points to a different location. ...
2
1835
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 Method2Run. If the clientType is A, it would run ClientInfoA function. If it is clientType B, it would run the ClientInfoB function. Based on the value of Method2Run, how would I run the function dynamically? I know that there are many ways not to...
5
3037
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? In other words, suppose that I have a generic pointer : void * f_ptr; I know that this pointer points to a fuction. I also know the function
5
2464
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 enlarges the map, I want to hide my navigation table etc, maximising the viewing area. I've been working on this for 5 hours now, so far I have as detailed below - Which rund with out error, but the final function never gets called. Any help/suggestions...
35
2900
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 been extremely successful for us so far but now I run into a license nightmare. Some the libraries we wrapped using SWIG are under GPL but the applications we are distributing are not (mainly because
3
1383
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 original function's functionality. So, for the first part, I'm looking for some way to do the following: if (hasMember(object o, string member){ //Processing
5
2224
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() from it: <code>
15
8213
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 Delegate. My testing showed that actually it was six times faster: 0.5 seconds for 100,000 iterations versus 3.1 seconds. Can anyone explain why? Something in the way I coded it? I'd appreciate any insights. Here's the code (in a Windows Form...
6
11582
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 another convention unless they have an ellipsis argument.) I can force GCC and other compilers to use such a convention by declaring all methods with an ellipsis, but I'd rather not clutter my method definitions with these.
0
9579
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10326
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10317
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10075
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9143
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6851
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5651
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3815
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2990
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.