Sending Function as Argument to Another Function
<p>I have came across this logic:</p>

<pre><code>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)
</code></pre>

<p>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).  </p>

<p>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). </p>

<p>So while it is considered an advanced technique, it is hardly uncommon to see it in Python. Python even has a language keyword (<code>lambda</code>) 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 <code>map</code>, <code>filter</code>, and <code>reduce</code>, 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.</p>

python