2

I am trying to "invert" map (same function, multiple arguments) in a case where I have multiple function that I want to apply to the same argument. I am trying to find a more function approach to replace the classical

arg = "My fixed argument"
list_of_functions = [f, g, h] #note that they all have the same signature
[fun(arg) for fun in list_of_functions]

The only thing I could come up with is

map(lambda x: x(arg), list_of_functions)

which is not really great.

3
  • 1
    Make sure you tell the Haskell people that list comprehensions aren't functional... Commented Nov 11, 2015 at 20:25
  • 1
    Bad phrasing. I really don't want to start a war with the Haskell people :) Commented Nov 11, 2015 at 20:47
  • Possible duplicate of Apply list of functions on an object in Python Commented May 10, 2019 at 13:35

2 Answers 2

4

You can try:

from operator import methodcaller

map(methodcaller('__call__', arg), list_of_functions)

The operator module also has similar functions for getting fixed attributes or items out of an object, often useful in functional-esque programming style. Nothing directly for calling a callable, but methodcaller is close enough.

Though, I personally like list comprehension more in this case. Maybe if there was a direct equivalent in the operator module, like:

def functioncaller(*args, **kwargs):
    return lambda fun:fun(*args, **kwargs)

…to use it as:

map(functioncaller(arg), list_of_functions)

…then maybe it would be convenient enough?

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

3 Comments

Not sure if I agree. Isn't this creating (f.arg(), g.arg(), h.arg())?
@meto: ah, sorry, you found my post before I realized my mistake. It's fixed now ;-)
Thanks for the correction. I agree that this looks uglier than the list comprehensions. I would really like to see a functioncaller function, even if I understand that the usage would be quite limited
1

In Python 3 your map() example returns a map object, so the functions are only called when it is iterated over, which is at least lazy.

3 Comments

Of course, the same holds for the generator expression (fun(arg) for fun in list_of_functions).
Thanks for the note, but my question is more about the syntax. For now I don't really care if i get back a generator or an actual object
I'd go with the generator expression in JAB's comment if you are using a new enough version of Python.

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.