Reputation: 21
Dictionary was generated from config file:
dict_1 = {
'type1' : 'function1()',
'type2' : 'function2()',
'type3' : 'function3()'
}
Variable x contains any key from this dictionary. I tried to call a function as follows:
dict_1[x]
Does anybody know alternative for exec function to run this statement?
Upvotes: 2
Views: 1894
Reputation: 26570
As mentioned in the comment, to help illustrate this better for you, this is your best approach:
def foo():
print("I was just called")
def boo():
print("I was called too")
dict_of_methods = {
"type1": foo,
"type2": boo
}
dict_of_methods.get('type1')()
dict_of_methods.get('type2')()
If you have deal with the string representation of the method in your dictionary, then you have to be cautious about your local and global scope when using the following two commands, but your options are as:
locals()[dict_of_methods.get('type1')]()
globals()[dict_of_methods.get('type1')]()
Read this to understand:
http://www.diveintopython.net/html_processing/locals_and_globals.html
Upvotes: 5
Reputation: 5261
I don't know what exactly you mean when you say that the dict is generated from a config file. If you were constructing the dict in the script you would write:
dict_1 = {
'type1' : function1,
'type2' : function2,
'type3' : function3
}
and call an element like this:
dict_1['type1']()
If you're getting the function names from a config file, and the names refer to functions defined in your script, then you could create a a dict in the script that maps all the relevant function names to the associated functions (or perhaps use the dict returned by globals()
) to construct dict_1
.
Upvotes: 1
Reputation: 966
If your functions are predefined in your code and you are just using your configuration file to pick which of them to call you can use the python eval function
d = {"type1" : "function1()"}
def function1():
print( "Hello from function 1")
eval(d["type1"])
Hello from function 1
Upvotes: -1