Question

How would one use higher-order functions (functions returning other functions) in Python?

This is my JavaScript example, whose programming concept I would like to use in Python as well. Let's say, for example, that I would like to wrap a string in an HTML element. In JavaScript, it would look like this:

var wrapInElement = function(ele) {
    return function(inp) {
        return "<" + ele + ">" + inp + "</" + ele + ">";
    };
};

And then I would use it like this:

var names = ["Mike", "Tony", "John"];
names.map(wrapInElement("p"));

How could this look like in Python? Is there a way to write functions that return customized functions like in the example above? One could also write a class in Python that accomplishes this task but wouldn't that be too much for such a basic task?

Was it helpful?

Solution

In python, functions are first-class citizens, just like in javascript:

def adder(n):
    def add_func(x):
        return x + n
    return add_func

add3 = adder(3)
print map(add3, [1,2,3])  # [4, 5, 6]

This is not the only option, for example adder can also be written as:

def adder(n):
    return lambda x: x + n

Note that functional style is not quite pythonic, when possible, we prefer comprehensions and generators over high-order functions:

wrapped = ["<p>{}</p>".format(name) for name in names]

OTHER TIPS

Your JavaScript example can be rewritten (arguably more cleanly) using partial application:

// depends on `_` -- see link above
function wrapInElement(ele, inp) {
    return "<" + ele + ">" + inp + "</" + ele + ">";
};

var f = _.partial(wrapInElement, "p")

... then use f as a normal function ...

And pretty much the same way in Python:

from functools import partial

def wrap_in_element(ele, inp):
    return "<%s>%s</%s>" % (ele, inp, ele)

f = partial(wrap_in_element, "p")

... then use f as a normal function ...

While yes, one can use higher-order functions in both Python and JavaScript, if you find yourself returning functions in order to roll-your-own partial application mechanism, you should realize that this ugliness (which appears in both languages' examples) is not necessary thanks to the awesome libraries out there.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top