<div dir="ltr"><div><div>I'm sure this could be improved upon and/or is discussed more eloquently elsewhere.  I'm inviting links, comments.  <br><br>I recall our own discussion here on edu-sig where we played with <br>
<br>@D<br>def f(x):...<br><br>as taking a Derivative of f.  Guido didn't think it was such a great idea as I recall.<br><br><a href="http://aroberge.blogspot.com/2005/04/computing-derivatives-using-python.html">http://aroberge.blogspot.com/2005/04/computing-derivatives-using-python.html</a><br>
<br>Kirby<br><br><br></div>===<br><br>Excerpt from a note to a student:<br><br>Why do we need decorators you ask?<br><br>We should go back to Guido's original complaint about the old way of doing <br>it, which was to define a method, say m, and then go m = staticmethod(m)<br>
at the end, to apply a transformation to the method, which would not change<br>its name, but would make it a static method, meaning it did not require self,<br>nor even the class as a first argument:<br><br>>>> class Foo:<br>
...     def add(a,b):<br>...         return a + b<br>...     add = staticmethod(add)<br>... <br>>>> obj = Foo()<br>>>> obj.add(2,3)<br>5<br><br>Likewise property( ) and classmethod( ):  these were applied after method m<br>
had already been defined, retroactively as it were.  That was Guido's complaint,<br>the fact that transformations were applied as a footnote, as it were, rather than<br>boldly up front (at the top).<br><br>All a decorator is, is syntax for saying "the function or class defined below <br>
is going to be put through @this and @that ringer where 'ringer' means<br>other classes or functions".  It's a way of indicating the transformations up <br>front, versus waiting until the bottom / end of method, which Guido thought<br>
a place of relative obscurity, maybe on some next page.  Buried.  Harder to<br>parse.<br><br>These two say the same thing:<br><br>class A:<br>  pass # could go on for pages<br>A = foo(bar(A))<br><br><br>@foo<br>@bar<br>class A:<br>
  pass<br><br>Like so much of Python, such syntax may be put to nefarious uses, <br>i.e. Python gives you more than enough rope to hang yourself with its<br>liberal / powerful syntax.  Misuses of decorators are certainly possible,<br>
where a "misuse" might be anything that complicates, obscures, <br>confuses.<br><br>Back to the original example:<br><br>>>> class Foo:<br>...     @staticmethod<br>...     def add(a,b):<br>...         return a + b<br>
<br>has a certain elegance about it.  In retrospect, the innovation has proved powerful.<br>As Raymond Hettinger recounts in his recent Pycon keynotes, it was a case of <br>Guido asking everyone for feedback, their coming to near consensus in a rare <br>
moment, and him doing something else anyway.  Something like that.<br><br>-Kirby<br><br></div></div>