Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a dictionary to select function to execute

I am trying to use functional programming to create a dictionary containing a key and a function to execute:

myDict={} myItems=("P1","P2","P3",...."Pn") def myMain(key):     def ExecP1():         pass     def ExecP2():         pass     def ExecP3():         pass         ...     def ExecPn():         pass   

Now, I have seen a code used to find the defined functions in a module, and I need to do something like this:

    for myitem in myItems:         myDict[myitem] = ??? #to dynamically find the corresponding function 

So my question is, How do I make a list of all the Exec functions and then assign them to the desired item using the a dictionary? so at the end I will have myDict["P1"]() #this will call ExecP1()

My real problem is that I have tons of those items and I making a library that will handle them so the final user only needs to call myMain("P1")

I think using the inspect module, but I am not so sure how to do it.

My reason to avoid:

def ExecPn():     pass myDict["Pn"]=ExecPn 

is that I have to protect code as I am using it to provide a scripting feature within my application.

like image 503
JohnnyDH Avatar asked Feb 06 '12 22:02

JohnnyDH


People also ask

How do you call a function from a dictionary in Python?

Given a dictionary, assign its keys as function calls. Case 1 : Without Params. The way that is employed to achieve this task is that, function name is kept as dictionary values, and while calling with keys, brackets '()' are added.

Can we pass dictionary to a function?

Passing Dictionary as an argument In Python, everything is an object, so the dictionary can be passed as an argument to a function like other variables are passed.

How do you apply a function to each value of a dictionary?

You can use the toolz. valmap() function to apply a function to the dictionary's values. Similarly, to apply function to keys of a dictionary, use toolz. keymap() function and to apply function to items of a dictionary, use toolz.


1 Answers

Simplify, simplify, simplify:

def p1(args):     whatever  def p2(more args):     whatever  myDict = {     "P1": p1,     "P2": p2,     ...     "Pn": pn }  def myMain(name):     myDict[name]() 

That's all you need.


You might consider the use of dict.get with a callable default if name refers to an invalid function—

def myMain(name):     myDict.get(name, lambda: 'Invalid')() 

(Picked this neat trick up from Martijn Pieters)

like image 154
S.Lott Avatar answered Sep 23 '22 23:09

S.Lott