JohnnyDH JohnnyDH - 3 months ago 9
Python Question

Python: Using a dictionary to select function to execute

Hello I am new in Python, 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 as I said, I am new and I am not so sure how to do it.

Thank you!

UPDATE

Since it appears that people is confusing about my reasons to avoid:

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


I have to protect code as I am using it to provide Scripting feature within my application.

Daniel H

Answer

Not proud of it, but:

def myMain(key):
    def ExecP1():
        pass
    def ExecP2():
        pass
    def ExecP3():
        pass
    def ExecPn():
        pass 
    locals()['Exec' + key]()

I do however recommend that you put those in a module/class whatever, this is truly horrible.