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):
print(arg1)
def bar(arg2,arg3):
print (arg2,arg3)
return bar
foo("hello")("hello","world")
>>>
hello
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.
3
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");
Output:
Panic: Universe imploding
1