alphanumeric
alphanumeric

Reputation: 19329

Sending Function as Argument to Another Function

I have came across this logic:

def f2(f):
  def g(arg):
      return 2 * f(arg)
  return g

def f1(arg):
    return arg + 1

f_2 = f2(f1)
print f_2(3)

From a first glance it may seem it is a very simple code. But it takes some time to figure out what is going on here. Sending a function as an argument to another function is unusual to me. While it works I wonder if a technique like this should be avoided (since it does appear quite confusing at first).

Upvotes: 0

Views: 57

Answers (1)

kindall
kindall

Reputation: 184131

The passing of functions to other functions is a common idiom in so-called functional programming languages like LISP, Scheme, Haskell, etc. Python is sometimes referred to as a "multi-paradigm language" because it has some features of functional languages (as well as of imperative/structured and object-oriented languages).

So while it is considered an advanced technique, it is hardly uncommon to see it in Python. Python even has a language keyword (lambda) to let you define short anonymous functions "in line" when calling a function, so you don't have to give them a name and define them elsewhere. It also has built-in functions like map, filter, and reduce, which are explicitly designed to work with functions passed in to them; these are borrowed from the aforementioned functional languages. And a commonly-used language feature, decorators, is basically a function that takes a function and returns a function.

Upvotes: 2

Related Questions