alwbtc
alwbtc

Reputation: 29445

Python: How to pass functions to another function as arguments?

I have 2 custom functions:

f(), g()

I want to pass all months to them, and pass them another function as follows:

x(f("Jan"), g("Jan"), f("Feb"), g("Feb"), f("Mar"), g("Mar"), ...)

How is it done in short way?

Best Regards

Upvotes: 0

Views: 218

Answers (1)

Gareth Latty
Gareth Latty

Reputation: 89007

So, first of all, we want to call f() and g() on each item of a list. We can do this with a list comprehension:

[(f(month), g(month)) for month in months]

This produces a list of tuples, but we want a flat list, so we use itertools.chain.from_iterable() to flatten it (or in this case, just a generator expression):

from itertools import chain

chain.from_iterable((f(month), g(month)) for month in months)

Then we unpack this iterable into the arguments for x():

x(*chain.from_iterable((f(month), g(month)) for month in months))

Edit: If you wish to pass the functions ready to be executed with that parameter, without executing them, it's functools.partial() to the rescue:

from functools import partial

[(partial(f, month), partial(g, month)) for month in months]

This would mean the parameters to x() would be functions that, when called, run f() or g() as appropriate, with the month filled as given to the partial. This can, of course, be expanded out in the same way as before.

Upvotes: 5

Related Questions