Marc Frame Marc Frame - 5 months ago 8
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):
print('THIS IS WORKING')
#print(i)
i+=1


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.

Cheers,

Marc

Answer

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
Comments