Most pythonic way to write a high order function

This should be a very simple question, but I'm wondering what is the most pythonic way to handle a high order function. I have already defined f

and g

:

def f(x):
    return x**2

def g(x):
    return x**3

def gen_func(f,g):
    def func(x):
        return f(x)+g(x)
    return func

wanted_func = gen_func(f, g)

      

or

import functools

def gen_func(f,g,x):
    return f(x)+g(x)

wanted_func = functools.partial(gen_func, f, g)

      

And maybe there is a point I could skip if the two entries are different?

+3


source to share


1 answer


Well, if you don't use gen_func

elsewhere, you can eliminate it in favor of the following one-liner:

wanted_func = functools.partial(lambda f, g, x: f(x) + g(x), f, g)

      

... but this is not as readable and the partial function application is actually redundant. I could just write:

wanted_func = lambda x: f(x) + g(x)

      




But as examples for you, there is no difference between them (which I know), so this is indeed the case. I would avoid the "pythonic" dogma and just use whatever you think is most readable and what is most appropriate for your particular use case, not what the Python community thinks is right.

Remember that Python is a language, and like spoken languages, prescribing rules about how they are used tend to limit expressiveness. I like to compare it to Newspeak .

+1


source







All Articles