Search code examples
pythonfunctools

Most pythonic way to write high order function


It should be a very basic question but I wonder what's the most pythonic way to handle high order function. I have f and g already defined:

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 there may be a point I could miss where these two writing differ?


Solution

  • Well, assuming you don't use gen_func elsewhere, you could eliminate it in favour of the following one-liner:

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

    ...but this isn't so readable, and the partial function application is actually redundant. Might as well just write:

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

    But, as for you examples, there are no differences (that I know of) between them, so really it's up to you. I would eschew "pythonic" dogma and just use whatever you consider most readable and whatever is most appropriate for your particular use case, not what the Python community considers correct.

    Remember that Python is a language and, just like with spoken languages, prescriptive rules about how they're used tend to limit expressiveness. I like to compare it to Newspeak.