Python Decorators: Wonderful and beautiful syntactic sugar(avinashv.net)
avinashv.net
Python Decorators: Wonderful and beautiful syntactic sugar
http://avinashv.net/2008/04/python-decorators-syntactic-sugar/
5 comments
I agree, but as I tried to make clear in the article, I've only tried to make the code as generalized as possible. For the memoize class for example, you wouldn't care. For the safe class, you'd definitely write in more exceptions to handle more issues your source might have. In this process, you'd be writing the proper method signature in.
You're right though, I should have made that clearer.
You're right though, I should have made that clearer.
I first came across decorators in TurboGears where they are used extensively for exposing methods, pagination etc (similar to pylons and Django).
They are very useful and insanely easy to use in python.
They are very useful and insanely easy to use in python.
Not really familiar with TurboGears, but it's always awesome to see an app leveraging a language's natural power and flexibility.
I concur about decorators being "insanely easy to use"--taking the memoization example I presented in the article; it's far, far simpler to tack on "@memoize" than to incorporate it into the flow of a function and risk losing clarity. I am sure TurboGears (and Django/Pylons) authors love that you can decorate something with @login_required (or equivalent) and have that method exposed to authentication.
I concur about decorators being "insanely easy to use"--taking the memoization example I presented in the article; it's far, far simpler to tack on "@memoize" than to incorporate it into the flow of a function and risk losing clarity. I am sure TurboGears (and Django/Pylons) authors love that you can decorate something with @login_required (or equivalent) and have that method exposed to authentication.
This looks similar to aspect-oriented programming.
For example, post-sharp (aspects for c-sharp).
Usually this is not a problem, but some people want to see the correct method signature when they look up the documentation (often auto-generated) for a function. And there are some programs that inspect the method signature and expect it to be correct.
http://www.phyast.pitt.edu/~micheles/python/documentation.ht... provides more details on this subject, as well as a library to mitigate this problem. I believe functools.wraps in python2.5 also solves this problem: http://docs.python.org/lib/module-functools.html