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

Given a string - execute a function by the same name

I'm parsing a simple file and given a line's keyword, would like to call
the equivalently named function.

There are 3 ways I can think to do this (other than a long if/elif
construct):

1. eval()

2. Convert my functions to methods and use getattr( myClass, "method" )

3. Place all my functions in dictionary and lookup the function to be
called

Any suggestions on the "best" way to do this?

Thank you,
Malcolm
Jun 27 '08 #1
6 1397
One solution may be to use globals():
>>globals()['foo']()
Regards,
Marek
Jun 27 '08 #2
On Apr 28, 9:33 am, pyt...@bdurham.com wrote:
I'm parsing a simple file and given a line's keyword, would like to call
the equivalently named function.

There are 3 ways I can think to do this (other than a long if/elif
construct):

1. eval()

2. Convert my functions to methods and use getattr( myClass, "method" )

3. Place all my functions in dictionary and lookup the function to be
called

Any suggestions on the "best" way to do this?

Thank you,
Malcolm
You can always import yourself and use getattr on that module.

in file "mytest.py":

def foo():
print "foo called"

def call_by_name(name, *args, **kwargs):
import mytest

f = getattr(mytest, "foo")
f(*args, **kwargs)

if __name__ == "__main__":
call_by_name('foo')

Alternatively you can import __main__ if you are always going to be
running directly from that file.

Matt
Jun 27 '08 #3
py****@bdurham.com writes:
I'm parsing a simple file and given a line's keyword, would like to call
the equivalently named function.

There are 3 ways I can think to do this (other than a long if/elif
construct):

1. eval()

2. Convert my functions to methods and use getattr( myClass, "method" )

3. Place all my functions in dictionary and lookup the function to be
called
4. Put all my functions in a module and use getattr(module, 'function')

--
Arnaud

Jun 27 '08 #4
py****@bdurham.com a écrit :
I'm parsing a simple file and given a line's keyword, would like to call
the equivalently named function.

There are 3 ways I can think to do this (other than a long if/elif
construct):

1. eval()

2. Convert my functions to methods and use getattr( myClass, "method" )

3. Place all my functions in dictionary and lookup the function to be
called
4. Place all your functions in a module and use getattr(the_module, "func")

5. use globals().get("func")
Any suggestions on the "best" way to do this?
#1 is the worst possible solution, and #2 doesn't make sens if you don't
need methods.

#4 is simple but can be problematic since these functions are not
necessarily related enough to make for a module with hi cohesion and low
coupling.

#5 is the simplest solution, but can be dangerous, since just any
function in the global namespace (which includes the builtins...) can be
called.

#3 is a bit heaviest to setup and maintain, but much more secure since
you explicitely choose the availables functions.

Depending on the context (ie: where this 'simple file' comes from), I'd
choose #3 or #5.

My 2 cents...
Jun 27 '08 #5
<py****@bdurham.comwrote in message
news:ma**************************************@pyth on.org...
I'm parsing a simple file and given a line's keyword, would like to call
the equivalently named function.
No, actually, you woudn't :-) Doing so means that if your programs input
specification ever changes, you have to rename all of the relevant
functions. Moreover, it leaves open the possibility that you might wind up
calling a function you didn't intend.

The right way to solve this kind of problem is to list all the functions you
wish to be able to call in this way, and then explicitly define a mapping
from keywords to the appropriate functions. Which is exactly what you're
doing in
3. Place all my functions in dictionary and lookup the function to be
called

Jun 27 '08 #6
Andrew,
I'm parsing a simple file and given a line's keyword, would like to call the equivalently named function.
No, actually, you wouldn't :-) Doing so means that if your programs input specification ever changes, you have to rename all of the relevant functions. Moreover, it leaves open the possibility that you might wind up calling a function you didn't intend.
I'm using Arnaud Delobelle's technique (see below) to insure that only
the appropriate methods are called. A great, practical example of a
decorator.

<snip>
functions = {}

def register(func):
functions[func.__name__] = func
return func

@register
def foo(): print "Foo!"

@register
def bar(): print "Bar!"
>>functions
{'foo': <function foo at 0x6f2f0>, 'bar': <function bar at 0x6f330>}
>>functions['bar']()
Bar!
</snip>

Thanks for your feedback,

Malcolm
Jun 27 '08 #7

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

Similar topics

7
by: Andrzej | last post by:
Is it possible to call a function which name is given by a string? Let assume that I created a program which call some functions for example void f1(void), void f2(void), void f3(void). ...
3
by: carl.barrett | last post by:
Hi, I have a number of buttons on a form which run mailmerges. Next to each button is a text box/control that the user enters a date into when the letter was created/merged. When the user...
1
by: Hugh | last post by:
Hi all, Is it possible to execute a function by getting the name of the function to execute from a string? For example: string FunctionName = "MyFunction"; which would execute MyFunction()....
0
by: Gary Herron | last post by:
python@bdurham.com wrote: You are on the right track with (2), but you need not do any conversion. All objects that have attributes (and a function is an attribute) can be looked up with...
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: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
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: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
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
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...
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,...

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.