Skip to content Skip to sidebar Skip to footer

Most Pythonic Way To Call A List Of Functions

I have a list of functions, like so: def foo(a, b): # do stuff return True # or False def bar(c): # do stuff return False # or True def baz(d, e, f): # do stu

Solution 1:

The and operator also short-circuits, so you can do:

if foo(1, 2) and bar(3) and baz(4, 5, 6):
    print("Success")

If you want a more general way, you can make a list of lambdas.

steps = [
    lambda: foo(1, 2), 
    lambda: bar(3), 
    lambda: baz(4, 5, 6)
]
if all(f() for f in steps):
    print("Success")

or a list of tuples:

steps = [
    (foo, (1, 2)), 
    (bar, (3)), 
    (baz, (4, 5, 6))
]
if all(f(*args) for f, args in steps):
    print("Success")

Solution 2:

Use all like this:

steps = [foo, bar, baz]
arguments = [[1, 2], [3], [4, 5, 6]]
if all(func(*args) for func, args in zip(steps, arguments)):
    print("Success!")

Solution 3:

Functions are hashable objects, so you can use them as keys of dicts.

funcs = {
    foo: (1, 2),
    bar: (3,),
    baz: (4, 5, 6),
}

This is a little cleaner than separate lists of functions and arguments, because it prevents the lists from falling out of sync.

Now just use all:

if all(f(*args) for f, args in funcs.items()):
    print("Success!")

Dictionaries are ordered in the current version of Python (3.8.0), as well as the previous minor version (3.7.x). If you use an older version of the language (< 3.7), you may still do the same with a collections.OrderedDict.

This approach does not work if you want to call the same function more than once, because dictionary keys must be unique. In this case you should use a list of pairs instead:

steps = [
    (foo, (1, 2)),
    (bar, (3,)),
    (baz, (4, 5, 6)),
    (foo, (7, 8)),
]

Post a Comment for "Most Pythonic Way To Call A List Of Functions"