0

I want to select a function based on the value of a dictionary:

dict = {"func_selector":"func1", "param_value":"some_value"}

# defined a function
def func1(param):
  # some function code

Now, I want to select the function based on the value of some key, so that it can achieve something like:

# calling a function based on some dict value
dict["func_selector"](dict["param_value"])

The syntax is probably wrong, but I am wondering if it is possible to do that in Python or something similar.

CodeMouse92
  • 6,840
  • 14
  • 73
  • 130
daiyue
  • 7,196
  • 25
  • 82
  • 149
  • 3
    Why are you not storing the function itself rather than a string? `dict = {"func_selector":func1, "param_value":"some_value"}` – Delgan Apr 19 '16 at 16:28

2 Answers2

1

Try storing the value of the function in the dictionary, instead of its name:

def func1(param):
    print "func1, param=%r" % (param,)

d = {"func_selector":func1, "param_value": "some value"}

Then you can say:

>>> d['func_selector'](d['param_value'])
func1, param='some value'
Phil Hunt
  • 507
  • 1
  • 4
  • 15
1

The best approach IMO is do it like this

def func1(param):
     #code

some_value = ... #The value you need
my_dict = {"func_selector": func1, "param_value": some_value }

And then

my_dict["func_selector"](my_dict["param_value"])

Now, if you only have the name of the function you need to call getattr

And call it

getattr(my_class, my_dict["func_selector"])(my_dict["param_value"])

my_class is the class which contains the method. If it's not in a class I think you can pass self

Mr. E
  • 2,070
  • 11
  • 23