473,404 Members | 2,187 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,404 software developers and data experts.

[Beginner] Calling a function by its name in a string

Hi all:

Is there a metalanguage capability in Python (I know there are many) to
call a function having its name in a string?

Something like:
__call__("foo")

instead of:
foo()

Regards,
Tito
Jul 27 '05 #1
11 1888
On 7/27/05, Tito <ti*******************@gmail.com> wrote:
Hi all:

Is there a metalanguage capability in Python (I know there are many) to
call a function having its name in a string?

Something like:
__call__("foo")

instead of:
foo()

def foo(): print "foobarred" .... foo() foobarred eval("foo()") foobarred


Peace
Bill Mill
bill.mill at gmail.com
Jul 27 '05 #2
Tito wrote:
Hi all:

Is there a metalanguage capability in Python (I know there are many) to
call a function having its name in a string?

Something like:
__call__("foo")

instead of:
foo()

Regards,
Tito

eval('foo()') should do, but it's said a bad practice ;)
Jul 27 '05 #3
Tito wrote:
Hi all:

Is there a metalanguage capability in Python (I know there are many) to
call a function having its name in a string?

Something like:
__call__("foo")

instead of:
foo()


locals()["foo"]() will be a little more predictable than eval("foo()").
--
Michael Hoffman
Jul 27 '05 #4
On 2005-07-27, Paolino <pa*************@gmail.com> wrote:
Is there a metalanguage capability in Python (I know there are many) to
call a function having its name in a string?
eval('foo()') should do, but it's said a bad practice ;)


An alternative to eval() is:
def foo(): .... print "foo was called"
.... s = "foo"
globals()[s]() foo was called


--
Grant Edwards grante Yow! I'm meditating on
at the FORMALDEHYDE and the
visi.com ASBESTOS leaking into my
PERSONAL SPACE!!
Jul 27 '05 #5
Thank you both for your quick answers.

What I wanted is to parameterize a function with another member
function, like this:

def printFunctionForEach(collection, functionName):
for elem in collection:
print eval("elem." + functionName + "()")

Moreover, I wanted to do it with a property:

def printPropertyForEach(collection, propertyName):
for elem in collection:
print eval("elem." + propertyName)

Is there another approach to do it?

Regards,
Tito
Jul 27 '05 #6
> Thank you both for your quick answers.

Thank you *all* for your quick answers.

Jul 27 '05 #7
Tito <ti*******************@gmail.com> writes:
def printPropertyForEach(collection, propertyName):
for elem in collection:
print eval("elem." + propertyName)

Is there another approach to do it?


Yes, use the getattr function:

for elem in collection:
print getattr(elem, propertyName)
Jul 27 '05 #8
On 7/27/05, Tito <ti*******************@gmail.com> wrote:
Thank you both for your quick answers.

What I wanted is to parameterize a function with another member
function, like this:

def printFunctionForEach(collection, functionName):
for elem in collection:
print eval("elem." + functionName + "()")

Moreover, I wanted to do it with a property:

def printPropertyForEach(collection, propertyName):
for elem in collection:
print eval("elem." + propertyName)

Is there another approach to do it?


Sure, piece of cake:
class test: .... def func1(self): print 'func1 called'
.... class test2: .... def func1(self): print 'other func1'
.... x = [test(), test2(), test()]
def call_this_func(lst, func_name): .... for e in lst:
.... getattr(e, func_name)()
.... call_this_func(x, 'func1') func1 called
other func1
func1 called


Note that the getattr raises an AttributeError if func_name doesn't
exist in the object; you should probably wrap it in a try/except.

Peace
Bill Mill
bill.mill at gmail.com
Jul 27 '05 #9
Once again: thank you.
Jul 27 '05 #10
Tito wrote:
Thank you both for your quick answers.

What I wanted is to parameterize a function with another member
function, like this:

def printFunctionForEach(collection, functionName):
for elem in collection:
print eval("elem." + functionName + "()")
Note: "member function" is spelled "method" in Python.
Moreover, I wanted to do it with a property:

def printPropertyForEach(collection, propertyName):
for elem in collection:
print eval("elem." + propertyName)


And "property" (the way you are using it) is spelled "attribute".

In Python, properties are something else, similar to but more than just
attributes.

Use of such terms according to conventional Python usage will in future
make it somewhat easier to be understood and for you to understand the
responses.

Cheers,
-Peter
Jul 27 '05 #11
On Wed, 27 Jul 2005 14:18:25 -0400, Bill Mill wrote:
On 7/27/05, Tito <ti*******************@gmail.com> wrote:
Hi all:

Is there a metalanguage capability in Python (I know there are many) to
call a function having its name in a string?

Something like:
__call__("foo")

instead of:
foo()

def foo(): print "foobarred" ... foo() foobarred eval("foo()")

foobarred


Which is dangerous beyond belief if you are getting your string "foo()"
from a user, and if you aren't, you almost certainly can refactor your
code so you don't need eval.

You know, I really am getting sick of (1) people who ask how to shoot
themselves in the foot and (2) people who cheerfully load the gun and hand
it to them without a word of warning about the consequences. And then
we all act surprised when we learn about the latest virus or security hole
that allows a hostile user to use a music player or paint program to take
over the entire operating system. Or whatever.

"We're all adults here" only works for people who ARE adults. If you have
to ask about eval, you can't be trusted with it without at least a warning.
--
Steven.

Jul 27 '05 #12

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

Similar topics

8
by: Foxy Kav | last post by:
Hi everyone, Im currently doing first year UNI, taking a programming course in C++, for one project i have to create a simple array manipulator... that i have done, but i cant figure out how to...
39
by: TonyJeffs | last post by:
Great book - I like the way that unlike other books, AC++ explains as much as possible about every piece of code discussed, so I'm not left thinking, "well...OK... I get line 12, but I wonder what...
19
by: What-a-Tool | last post by:
I have a school project (ASP) in which I have to call three different ASP pages from three different and identical (except for the form "action", obviously) HTM pages. This I have no problem with....
10
by: headware | last post by:
I know that you can call the method of one from from inside another form by doing something like this Forms("MyForm").MyFunction(12, 34) However, you have to know that MyForm has a function...
3
by: Jerome Cohen | last post by:
AI am trying to call a third-party web service. this service expects an XML fragment that contains the request plus other parameter. adding the web reference created the syntax below(reference.vb)....
4
by: Henning M | last post by:
Hej All Im relativ new to VB.net and im trying to collect som device information using cfgmgr32.dll I use - Declare Function GetListLength Lib "cfgmgr32.dll" Alias...
3
by: Yourko | last post by:
Hello! I ame working on a hobby-project - a simple TCP/IP server. Its purpose (for now) is to act like a chat program: send all received data from one connected client to all others. First step is...
5
by: bd | last post by:
I keep getting this error: line(28): error C2664: 'convertString' : cannot convert parameter 1 from 'std::string ' to 'std::string' Here is my code: //...
4
by: raghuvendra | last post by:
Hi I have a jsp page with 4 columns: namely Category name , Category order, Input field and a submit button. All these are aligned in a row. And Each Category Name has its corresponding Category...
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...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
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...
0
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,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 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 a new...

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.