PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, November 4, 2022

[FIXED] How do you create a python list comprehension of lambdas?

 November 04, 2022     deferred-execution, lambda, list-comprehension, python     No comments   

Issue

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?


Solution

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

  • Documentation for functools.partial.


Answered By - CypherX
Answer Checked By - Mildred Charles (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing