1

I am using a dictionary/get construct as a switch case in Python. It looks similar to this one:

def switch_function(pluginID, param):
switcher = {
    'someid': somefunction(param),
}
return switch_function.get(pluginID, None)

However, i want to to extend the dictionary by another key value pair, which is defined in a conf file. I want a function head as an value. The function head should be the head of that function, which should be executed in the switch case, for a specific pluginid. The config file will look something like this:

[aSection]
pluginid='anotherid'
functionHead: anotherfunction2

Extending the dictionary should be easy, but is it possible to map a function head as an value inside a conf file?

Depa
  • 459
  • 8
  • 18

1 Answers1

1

The following example will give you an exec clause. Your dict should extend to something like this:

switcher[config["aSection"]["anotherid"])] = func

Then you need to define func to look something like this:

#CONF
#[aSection]
#pluginid='anotherid'
#functionHead: anotherfunction2

#PYTHON
#config is an instance of a config parser
def func (param):
  exec ("%s(param)" % config["aSection"]["functionHead"])

This will call a function called anotherfunction2 that you have previously defined. Call the func like this:

switcher[config["aSection"]["anotherid"])](param)

Hope this helps!

Andrei Tumbar
  • 490
  • 6
  • 15
  • I have to be honest, that i didn't fully understand your solution, but it gave me a hint how i can solve my problem. Instead of using exec like you did, i used eval. – Depa Jun 02 '16 at 02:00