Since functions are first class objects, you can pass around references to them without calling them, and call them later:
dictionary = {
"a":function_1, # No parens here anymore
"b":function_2, # ''
"c":function_3, # ''
}
for key,value in dictionary.items():
if key == something:
# "Calling" parens here, not in the dictionary values
wanted_variable = value()
Alternatively,
dictionary = {
"a":function_1, # No parens here anymore
"b":function_2, # ''
"c":function_3, # ''
}
func = dictionary.get(key)
if func:
wanted_variable = func()
Which ends up doing the same thing but without having to loop though the dictionary items.
For more complicated scenarios, when you want to capture an uncalled function but also the parameters to that function, there's also functools.partial
from functools import partial
dictionary = {
"a":partial(function_1, 123),
"b":partial(function_2, 456),
"c":partial(function_3, 789),
}
for key,value in dictionary.items():
if key == something:
# "Calling" parens here, not in the dictionary values
# This will actually call, for example, function_1(123).
wanted_variable = value()
For example:
from functools import partial
def foo(x):
print("x is", x)
wrapped_foo = partial(foo, 123)
# Pass wrapped_foo around however you want...
d = {'func': wrapped_foo}
# Call it later
d['func']() # Prints "foo is 123"