473,320 Members | 1,949 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,320 software developers and data experts.

programmatically calling a function

hi

i'd like to call a python function programmatically - when all i have
is the functions name as a string. i.e.
fnames = ['foo', 'bar']

for func in fnames:

#
# how do i call function 'func' when all i have is the name of the
function ???
#

def foo():

print 'foo'

def bar():

print 'bar'
i'd really appreciate any help the 'group' has to offer.
thanks
dave

Jul 18 '05 #1
9 3120
Dave Ekhaus wrote:
i'd like to call a python function programmatically - when all i
have is the functions name as a string. i.e.

fnames = ['foo', 'bar']
The usual answer at this point is to say that functions are
"first class objects" in Python, which basically means you
can haul around references to them instead of having to
refer to them indirectly with strings. This isn't always
possible, but see if this might be something you can do instead:

funcs = [foo, bar] # note: no quotation marks!

for func in funcs:
func(1, 2, 3) # call each function, passing three arguments...
for func in fnames:
# how do i call function 'func' when all i have is the name of the
function ???


To convert from the name to a reference, you'll still need access
to the functions, so often you don't really need to use the names
approach. Still, if you must, all you need to know is what namespace
the functions are defined in. If they're local to the current module,
you can use globals(), which returns a dictionary of global names
that you can index using the name:

fnames = ['foo', 'bar']
for name in fnames:
func = globals()[name]
func(1, 2, 3) # call function with three arguments, or whatever
-Peter
Jul 18 '05 #2
You might also want to take a peek at the getattr() function:

http://docs.python.org/lib/built-in-funcs.html#l2h-31

Jul 18 '05 #3
In article <2005030418250516807%dekhaus@maccom>,
Dave Ekhaus <de*****@mac.com> wrote:
hi

i'd like to call a python function programmatically - when all i have
is the functions name as a string. i.e.
fnames = ['foo', 'bar']

for func in fnames:

#
# how do i call function 'func' when all i have is the name of the
function ???
#

def foo():

print 'foo'

def bar():

print 'bar'
i'd really appreciate any help the 'group' has to offer.
thanks
dave

Dave,

I think eval might be what you're looking for:

f = eval('len')
length = f([1,2,3])
By the way, are you the Dave Ekhaus I used to work with at Kodak?

--
Doug Schwarz
dmschwarz&urgrad,rochester,edu
Make obvious changes to get real email address.
Jul 18 '05 #4
Doug Schwarz wrote:
Dave,

I think eval might be what you're looking for:

f = eval('len')
length = f([1,2,3])


But only if the string given to eval is checked thorougly for allowed
contents. Better use getattr.

Reinhold
Jul 18 '05 #5
In article <38*************@individual.net>,
Reinhold Birkenfeld <re************************@wolke7.net> wrote:
Doug Schwarz wrote:
Dave,

I think eval might be what you're looking for:

f = eval('len')
length = f([1,2,3])


But only if the string given to eval is checked thorougly for allowed
contents. Better use getattr.

Reinhold

Actually, upon reading Peter Hansen's reply more carefully, I wil defer
to his approach, namely,

def foo():
print "foo"

f = globals()["foo"]

as I suspect that it will be more efficient. You still need to make
sure that the string in question is one of the keys in the globals()
dictionary or else handle the error -- just as with eval.

I don't see how getattr solves the original problem. What, exactly, is
the first argument to getattr?

--
Doug Schwarz
dmschwarz&urgrad,rochester,edu
Make obvious changes to get real email address.
Jul 18 '05 #6
Doug Schwarz wrote:
> Dave,
>
> I think eval might be what you're looking for:
>
> f = eval('len')
> length = f([1,2,3])
But only if the string given to eval is checked thorougly for allowed
contents. Better use getattr.


Actually, upon reading Peter Hansen's reply more carefully, I wil defer
to his approach, namely,

def foo():
print "foo"

f = globals()["foo"]

as I suspect that it will be more efficient. You still need to make
sure that the string in question is one of the keys in the globals()
dictionary or else handle the error -- just as with eval.


Well, with eval, you need to really check the string before calling
eval, with globals() you just need to catch an KeyError, which is cheaper.
I don't see how getattr solves the original problem. What, exactly, is
the first argument to getattr?


If run at the toplevel, __main__. If the functions are in a module, this
module. But you are right, globals() is more understandable.

However, if the use case is as in the OP's example, Peter Hansen's first
approach is surely the fastest and most concise.
Reinhold
Jul 18 '05 #7

Doug Schwarz wrote:
I don't see how getattr solves the original problem. What, exactly, is the first argument to getattr?

mod = __import__(__this__)
f = getattr(mod,"foo")

I tend to prefer this over globals() because it seems a little less
magical to me, especially when setting a global. Either this or
gloabls() will work fine. Please don't use eval for stuff like this:
that's not what it's for and it has the potential to be dangerous.
--
CARL BANKS

Jul 18 '05 #8

Carl Banks wrote:
Doug Schwarz wrote:
I don't see how getattr solves the original problem. What,
exactly, is
the first argument to getattr?

mod = __import__(__this__)


That should be __import__(__name__)
Silly me.
--
CARL BANKS

Jul 18 '05 #9
I see lots of others have made suggestions, but here is a method
that I use frequently:

define a dictionary that contains references to your functions:

def foo():
..
.. whatever it does
..

def bar():
..
.. whatever it does
..

xfer={'foo', foo, 'bar', bar}

Then you can write

for fname in fnames:
xfer[fname](args)

May not be what you want, but seems like it is from your description.

-Larry
Dave Ekhaus wrote:
hi

i'd like to call a python function programmatically - when all i
have is the functions name as a string. i.e.
fnames = ['foo', 'bar']

for func in fnames:

#
# how do i call function 'func' when all i have is the name of the
function ???
#

def foo():

print 'foo'

def bar():

print 'bar'
i'd really appreciate any help the 'group' has to offer.
thanks
dave

Jul 18 '05 #10

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

Similar topics

5
by: Al Christoph | last post by:
I have a program that mixes wizard like behavior with random access to the various dialogs in the wizard. I do this by having each step map to a toolstripmenuitem. Users can randomly choose the...
13
by: aundro | last post by:
Hello, I've been looking on the web for a solution to this problem: I create a set of checkboxes, and 2 buttons: - one is labeled "All" - the other is labeled "None" Clicking "All" is...
14
by: Open Wound | last post by:
What method can I call to programmatically scroll a panel? There is ScrollControlIntoView() but I don't have a control to scroll into view. I just want the panel to scroll up by 100 pixels. ...
0
by: Gregory Khrapunovich | last post by:
Hi, I have a menu that generates "Click" events and handlers for the events. Now I need to raise one of these events programmatically. Calling the handler directly is not the same because it...
2
by: | last post by:
I've defined an ObjectDataSource against a dataset, and I can bind the ObjectDataSource's members to data controls. I'm wondering how to take the values in an ObjectDataSource and...
2
by: Buddy Robbins | last post by:
Hey folks, I am in desparate need of help to solve my problem. I have written a service that examines a table in a database, and creates a directory hierarchy based on data in the table. It...
15
by: Oleg Subachev | last post by:
I need to programmatically invoke from other class Click event of the Button on my Form. Button.OnClick method is protected, not public. How to perform this ? Oleg Subachev
3
by: Ken Fine | last post by:
I'm interested in programmatically manipulating groups of ASP.NET controls by type. Can someone suggest code for the following? Loop through, say, all label controls on a page, and assigning a...
8
by: =?Utf-8?B?UmljaA==?= | last post by:
My from contains a "Move Next" button. When the user clicks on the "Move Next" button - several procedures get invoked and eventually, the dataset underlying the form will display main data from...
0
by: DolphinDB | last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation. Take...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
0
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: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work

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.