Python: Confusing example of Functions as Objects
<p>When I was reasearching a bit about decorators, I stumbled upon some rather confusing code that i found perplexing in the way that it passes varibles and functions.</p>

<pre><code>def get_text(name):
    return "lorem ipsum, {0} dolor sit amet".format(name)

def p_decorate(func):
    def func_wrapper(name):
        return "&lt;p&gt;{0}&lt;/p&gt;".format(func(name))
    return func_wrapper

my_get_text = p_decorate(get_text)

print my_get_text("John")

# &lt;p&gt;Outputs lorem ipsum, John dolor sit amet&lt;/p&gt;
</code></pre>

<p>I understand the concept of passing functions as variables (which is cool) however the way that it was passed multiple times confused me. <code>my_get_text</code> has already been assigned to a function with an argument (another function). However, just after that we reference this new variable and pass arguments to it ("John"). The way that "John" gets transferred in <code>func_wrapper()</code> is also perplexing. </p>

<p>How is <code>my_get_text</code> able to receive more arguments and how is it passed to the inside functions?</p>

<p>Thank you</p>

<p>This is a demonstration of how decorators work: They basically wrap the decorated function into another internal function and return its reference.</p>

<ol>
<li>In your example, the call <code>my_get_text = p_decorate(get_text)</code> calls the function <code>p_decorate</code> with the wrappable function as a parameter (<code>get_text</code>).</li>
<li>The return value is a reference to a newly defined function which takes exactly one parameter <code>name</code>. This return value is assigned to your variable name <code>my_get_text</code></li>
<li><code>my_get_text</code> is now <em>callable</em>, because it's a function reference.</li>
<li>If you call <code>my_get_text</code>, it calls the function that was created by the decorator and hands over your parameter <code>name</code> (in your case <code>'John'</code>).</li>
<li>The function creates <code>&lt;p&gt;</code>-Tags and pushes a string between them. This string is obtained from the function call that you provided the decorator in step 1: It is the return value of the call that has been <em>decorated</em>.</li>
</ol>

<p>By the way, because the function <code>func_wrapper</code> is re-defined each time a function is decorated (see <em>closure</em>), the return value is a function reference that points to an entirely new function.<br>
Compare the memory addresses:</p>

<pre><code>a = p_decorate(get_text)
b = p_decorate(get_text)
print(a == b)
print(a)
print(b)

&gt;&gt;&gt; False
&gt;&gt;&gt; &lt;function func_wrapper at 0x02ADFF30&gt;
&gt;&gt;&gt; &lt;function func_wrapper at 0x02ADFF70&gt;
</code></pre>

<p>The functions are defined with the very same call, but since they are <em>closures</em>, the function pointer refers to another memory address (i.e. a different function).</p>

python function variables python-decorators