Marc Frame Marc Frame - 1 year ago 47
Python Question

how to point towards a method given variable python

possibleRequests = ['test', 'test1']

def inboxReader():
global inbox
tempInbox = []
tempInbox = inbox.inboxMessage #inboxMesage remains filled?
print(inbox.inboxMessage, 'inboxReader')
i = 0
while (i < len(tempInbox)):
if (tempInbox[i] in possibleRequests):

I want to be able to have possible requests point towards a method to run rather than have a long list of if statments. What am I able to do in order to have a variable point towards and run a method.



Answer Source

You can first create a dictionary of functions then refer to it with tempInbox[i]. Example code below:

def func_a(x):
    return x

def func_b(x):
    return x*10

tempInbox = (2,3)

fn_dict = {"a":func_a,"b":func_b}
print fn_dict["a"](tempInbox[0]) # returns 2
print fn_dict["b"](tempInbox[1]) # returns 30