How do you create a python list comprehension of lambdas?

Question:

I am trying create a list of lambdas for deferred execution using a list comprehension.
The below is a simple example.

def func_a(message: str) -> None:
    print('a: ' + message)
    
def func_b(message: str) -> None:
    print('b: ' + message)

msg = 'some message'
funcs = [func_a, func_b]
funcs_w_args = [lambda : func(msg) for func in funcs]

for func in funcs_w_args:
    func()

The result is

b: some message
b: some message

Whereas the desired result should be

a: some message
b: some message

Where am I going wrong?

Asked By: OldSchool

||

Answers:

Solution

What you are trying to achieve is defining partial functions (more generally). You can do this using functools.partial.

Here’s how:

from functools import partial

# Your Code
def func_a(message: str) -> None:
    print('a: ' + message)
    
def func_b(message: str) -> None:
    print('b: ' + message)

msg = 'some message'
funcs = [func_a, func_b]

# What I changed: a list of partially-defined functions
funcs_w_args = [partial(func, msg) for func in funcs]

# Now call partially defined functions
for func in funcs_w_args:
    func()

Output:

a: some message
b: some message

Refernces

Answered By: CypherX