Turning Strings into Functions

F

Freddy

How do you turn a string into a callable function? I'm writing a
program which takes user input and then looks up the associated
function to run from a shelved dictionary. So, I have a dictionary
with entries like this:
myDict["Case1"] = {"desc":"This is Case1", "func1": "Handler1",
"func2" : "Handler2", "args": "ACCEPT"}

Then my program gets the string "Case 1" from the user, and needs to
assign func1 and func2 as handlers for certain events.
The argument to the handlers are sockets, and I can't know in advance
what they will be.

I need to assign the handler function before it is called. So I need
to turn the string into a function (there IS a function in this module
called Handler1() ). I don't think I can use an exec call, because
that would require me to build a string with the argument first.

Any suggestions?

Freddy
 
R

Richard Brodie

How do you turn a string into a callable function? I'm writing a
program which takes user input and then looks up the associated
function to run from a shelved dictionary.

I see you have an answer already, so I'll give you a question.
Is there any particular reason why you are storing the name
of the function in the dictionary rather than the function itself?

i.e. myDict["Case1"] = {"desc":"This is Case1", "func1": Handler1} etc
 
F

Freddy

I guess I could do that. Right now I'm creating the use cases
dictionary in a totally separate module which knows nothing about my
main module's functions. But I will try either moving the code into my
current module, or including the testcases.py into my higher level
module.
Thanks for the suggestion.

Freddy

Richard Brodie said:
How do you turn a string into a callable function? I'm writing a
program which takes user input and then looks up the associated
function to run from a shelved dictionary.

I see you have an answer already, so I'll give you a question.
Is there any particular reason why you are storing the name
of the function in the dictionary rather than the function itself?

i.e. myDict["Case1"] = {"desc":"This is Case1", "func1": Handler1} etc
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,164
Messages
2,570,898
Members
47,439
Latest member
shasuze

Latest Threads

Top