-1

I have a lot of possible functions I can call, however I don't always need to call every function.

Is there a way I can pass a list of functions I would like to call, then dynamically call them?

In other words:

def GetDate():
    ..does stuff..
    return Date

def GetTime():
    ..does stuff..
    return Time

def GetLocation():
    ..does stuff..
    return Location


List_of_functions_to_call = ["GetDate","GetTime"]

def Call_functions(List = List_of_Functions_to_call):
    for i in List:
        ...????...
        ..# Function would then call GetDate() and GetTime()
Campo21
  • 197
  • 1
  • 12
  • 1
    How about... `i()`? Note that a mutable default argument like a list is a bad idea: https://stackoverflow.com/q/1132941/3001761 – jonrsharpe Feb 01 '18 at 16:26
  • I agree that a list would be a bad idea for this purpose, i was just trying to explain my question. – Campo21 Feb 01 '18 at 16:35
  • Functions are first class objects in Python, you can just do `[GetDate, GetTime]`, then `i()` works to call them. – jonrsharpe Feb 01 '18 at 16:36

1 Answers1

0

You could do something like this:

def main_function(action):
    return { '1': func_a, '2': func_b, '3': func_c, '4': func_d}.get(action)()

def func_a():
    return "a"
def func_b():
    return "b"
def func_c():
    return "c"
def func_d():
    return "d"

if __name__=="__main__":
   print(main_function('1'))

This code snippet print a as expected.

lmln
  • 107
  • 1
  • 10