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.
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.
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.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With