Note that there are some explanatory texts on larger screens.

plurals
  1. POWhy are Python decorators with arguments syntactically different from those without?
    primarykey
    data
    text
    <p><a href="http://www.artima.com/weblogs/viewpost.jsp?thread=240845" rel="nofollow">This article</a>, linked to a number of times from various stackoverflow questions, describes how decorators with arguments are syntactically different from those without arguments.</p> <ul> <li>Decorators without arguments: "Notice that <code>__init__()</code> is the only method called to perform decoration, and <code>__call__()</code> is called every time you call the decorated <code>sayHello()</code>."</li> <li>Decorators with arguments: "Now the process of decoration calls the constructor and then immediately invokes <code>__call__()</code>, which can only take a single argument (the function object) and must return the decorated function object that replaces the original. Notice that <code>__call__()</code> is now only invoked once, during decoration, and after that the decorated function that you return from <code>__call__()</code> is used for the actual calls."</li> </ul> <p>The explanation given in the article doesn't tell me why the language is set up this way:</p> <blockquote> <p>Although this behavior makes sense -- the constructor is now used to capture the decorator arguments, but the object <code>__call__()</code> can no longer be used as the decorated function call, so you must instead use <code>__call__()</code> to perform the decoration -- it is nonetheless surprising the first time you see it</p> </blockquote> <p>There are two related features of this setup that are uncomfortable for me:</p> <ol> <li>Why provide a way to make no-argument decorators that's not just a special case of the more general method for specifying decorators? And why use <code>__init__</code> and <code>__call__</code> in both, but have them mean different things?</li> <li>Why use <code>__call__</code> in the case of decorators with arguments for a purpose other than calling the decorated function (as the name suggests, at least coming from the no argument case)? Given that <code>__call__</code> is only invoked right after <code>__init__</code>, why not just pass the function to be decorated as an argument to <code>__init__</code> and handle everything that would happen in <code>__call__</code> in <code>__init__</code> instead?</li> </ol>
    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.
 

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