If you want to use the arguments (p1, p2, p3)
as flags, you could always pack those arguments as a list using *args
(see this, this and this) and put your functions in a list (yep, Python lets you do that) and get something like:
def f1():
return 1
def f2():
return 2
def f3():
return 3
def g(*ps):
functions = [f1, f2, f3]
for i, p in enumerate(ps):
if p == 1: # Could do just `if p:` (0 evaluates to False, anything else to True)
print(functions[i])() # Notice the () to actually call the function
if __name__ == "__main__":
print("Run 1 0 0")
g(1, 0, 0)
print("Run 1 1 0")
g(1, 1, 0)
print("Run 0 1 0")
g(0, 1, 0)
print("Run 1 1 1")
g(1, 1, 1)
As per ShadowRanger's comment to this answer, you could even shorten the code a bit more. For instance, using zip
:
def g(*ps):
functions = [f1, f2, f3]
for function, p in zip(functions, ps):
if p:
print(function())
Or using itertools.compress
(you'll need to import itertools
at the top of your file):
def g(*ps):
functions = [f1, f2, f3]
for function in itertools.compress(functions, ps):
print(function())