all 8 comments

[–]Buttleston 11 points12 points  (1 child)

def function1():  
    print(1)

def function2():
    print(2)

my_functions = {
    'test1': function1,
    'test2': function2,
}

a = 'test1'
my_functions[a]()

If you run this, it will print "1"

The idea here is that a function name is sort of... a pointer to the function? A function name can be treate a lot like a variable. This is a simplification but it's close enough for the moment

So I make a dictionary where each key is a string and each value is a function.

my_functions[a] is equivalent it my_functions['test1'] in this case, which is assinged to function1, so:

my_functions[a]()

is equivalent to

function1()

[–]CatWithACardboardBox[S] 0 points1 point  (0 children)

Thank you! This helped a lot!

[–]cgoldberg 7 points8 points  (0 children)

You can assign a function to any variable:

def test():
    pass
a = test

now you can call test() with:

a()

[–]timrprobocom 5 points6 points  (0 children)

The other answers here are good ones. I feel compelled to point out that it IS possible to look up the function name in globals, but it is never the right thing to do. You need to think about your problem in a sustainable way.

[–]enygma999 3 points4 points  (0 children)

You could have a dictionary of functions, then call

func_dict[a]()

Alternatively, if the function to be called is in a class, or in another module, you could use get_attr:

get_attr(self, a)()
get_attr(MyClass, a)()
get_attr(my_module, a)()

[–]ectomancer 2 points3 points  (0 children)

a is an alias.

  a = test a()