Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Decorators are actually just a shortcut to something you can do manually. This code:</p> <pre><code>@deco def myfunc(): print(" myfunc() called.") </code></pre> <p>Is equivalent to:</p> <pre><code>def myfunc(): print(" myfunc() called.") myfunc = deco(myfunc) </code></pre> <p>For the sake of discussing this, let's say the original were still available as <code>original_myfunc</code> (even though in reality it isn't).</p> <p>So, when you do this:</p> <pre><code>deco(myfunc)() </code></pre> <p>What you end up calling is:</p> <pre><code>deco(deco(original_myfunc))() </code></pre> <p>And if you trace through that, it should be obvious why it prints what you expected. But let's do the exercise anyway.</p> <p>First, you call <code>deco(original_myfunc)</code>, and it does this:</p> <pre><code>def kdeco(): print("before myfunc() called.") original_myfunc() print(" after myfunc() called.") </code></pre> <p>return kdeco</p> <p>So that returns a function that prints the "before", calls <code>original_myfunc</code>, then prints the "after".</p> <p>And now we pass <code>deco(original_myfunc)</code> to <code>deco</code> again, which does this:</p> <pre><code>def kdeco(): print("before myfunc() called.") deco(original_myfunc)() print(" after myfunc() called.") return kdeco </code></pre> <p>So, that returns a function that prints the "before", then calls <code>deco(original_myfunc)</code>—which itself prints the "before", calls <code>original_myfunc</code>, and prints "after"—then prints "after".</p> <p>That's why you get the output you do.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload