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