2

I have the following code:

def f1():
    print("f1")

def f2():
    print("f2")

flist = [f1,f2]

list(map(lambda x: x(), flist))

I need to get rid of lambda because it cannot be dumped using pickle.

Is there any function or construction that runs the function received as parameter ?

Here is the actually code I need to modify and remove the helper function "call":

from multiprocessing import Pool
def call(x):
    x()
p = Pool()
p.map(call, func_list)

2 Answers 2

2

You could try

[f() for f in flist]

Hope this helps :)

Sign up to request clarification or add additional context in comments.

3 Comments

I need to use the "map" function. This is just a piece of code from a large framework and i have to use it's "map"
@GabrielCiubotaru: Lamda functions are "anonymous functions". You could create a new function called for example callFunc(func) and pass a function object to it which callFunc calls: callFunc(func): func(). now the map would be: list(map(callFunc, flist))
i know, but i wonder if python have this already implemented. Since it have also the "functional programming" paradigm, i think "function application" is a must
2

The map function is not a desire approach for this task based on python documentation :

map Return an iterator that applies function to every item of iterable, yielding the results.

And here you are just dealing with functions and you want to call them, So you can use a list comprehension or loop over your function list and call them in anyway you like.

But if your functions return values I suggest to use list comprehension because here since you just print some text your functions return None and you will create an extra list :

>>> [func() for func in flist]
f1
f2
[None, None]

In this case a simple loop would be efficient :

>>> for func in flist:
...    func()
... 
f1
f2

And if your functions return values you can use a list comprehension :

>>> def f1():
...     return "f1"
... 
>>> def f2():
...     return "f2"
... 

>>> flist = [f1,f2]
>>> [func() for func in flist]
['f1', 'f2']

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.