The function foo, has a nested function; bar. Calling foo with a second set of arguments feeds them into bar if bar is returned at the end of foo. How does this work and what is it called?

Are there any uses for it over simply having a single set of arguments that calls the function normally?

def foo(arg1):
    def bar(arg2,arg3):
        print (arg2,arg3)
    return bar


hello world

This is called higher-order programming, or, using functions as first-class values. In this case, a function returning a function.

The use of it compared to simply having a single set of arguments only becomes apparent when the "second set of arguments" is not provided, i.e. when foo("hello") is used by itself (passed into another function or stored in a variable). This is usually only useful if, unlike in the example in the original question, arg1 is used inside of bar. The answer involving getErrorHandler illustrates this more useful case, which can also be thought of as forming a closure.

Though "having second set of arguments" may be a helpful mental model, and corresponds to the way it looks when "fully called" (saturated), these extra arguments don't really belong to foo, they belong to bar.

| improve this answer | |
  • Thanks for explaining that. We found it on a piece of code and couldn't work out what was going on our why it was called. – user124757 Oct 2 '14 at 7:29
  • there are a couple of other terms that apply to what is going on here. functional programming, closure and currying – Josiah Yoder Jun 7 '18 at 16:03
  • from a more object-oriented perspective, you can think of the outer function as a factory method, which produces a function object that conforms to some functional interface. Admittedly, as soon as I say "functional interface" we are back into a functional paradigm again, but this can help you to think about it in the context of Java if that helps. – Josiah Yoder Jun 7 '18 at 16:20

I can't speak to the Python-ness of this, but in schemes that frequently use function handlers/callbacks, I'll use your construct for creating these:

def getErrorHandler(message):
    def onError(error):
        print message + ":" + error
    return onError

panicHandler = getErrorHandler("Panic");
warningHandler = getErrorHandler("Warning");
panicHandler("Universe imploding");


Panic: Universe imploding
| improve this answer | |
  • Ah, that example helps clear it up after reading that other person's comment. Many thanks. – user124757 Oct 2 '14 at 8:05

Not the answer you're looking for? Browse other questions tagged or ask your own question.