I would replace "excellent" with "extremely thorough."
I would recommend the posted link for a first introduction -- it's short, explains decorators as clearly but more approachably, and talks about their application to classes, something the SO answer misses.
Thanks for the link. As a python newbie, the way that helped me best was going through the stack overflow link and then the posted article.
From what I understand its also important to understand when the decorator function is executed. Before or after the function it decorates.(I understand its also possible, that it executes both before and after).
Is this understanding correct?
The only thing I'd like to see more of with respect to decorators is discussion of real benefits. The concept is fairly simple it's the technique and resulting code organization that is interesting. Much like Lisp macros, it's important to know when not to use them and none of the tutorials I've seen really address that.
a good example, when working with the Jinja2 templating language, when you want to declare your own modifier, a function that's called within the templating language like {bit of text|awesomify}, you'd just need to write a function with a decorator on it, like
@jinja2_modifier
def awesomify(s):
return "%s is awesome" % s
(except it wasn't "jinja2_modifier", look it up in the docs)
The only thing that I might ever want from functional and symbolic programming paradigms that I can't imagine how to emulate with decorators would be the ability to transform the actual compiled function object in some way. Python decorators can add lots of new code, sure, but they don't get access to the syntax tree for the function object to be able to break it apart and transform it.
Mind you, I truly love Python decorators, but I just don't think the comparison to languages like LISP quite holds up. Maybe I'm just inexperienced, though...
I'm going to hell for this, but here goes. A couple years back I wrote a library called Transformana ( https://github.com/daeken/Transformana ) which allows you to manipulate ASTs via 'macros' in decorators. I apologize from the bottom of my heart to anyone who ends up maintaining code that utilizes this, but have fun.
Fellow hell-bound soul here. I didn't go nearly as far as you did. I decided it would be fun to have guards in Python and decorators were just the tool. I sketched this out as part of a talk at Open Source Bridge a few years back:
It'll let you redefine functions with different guard parameters. (@when("x=5"), @when("x>20"), etc.) Like you, I would also shudder to see this in production. But it was fun and shows off some of what's possible.
That would be nice! I poked around djangos source to see how they created decorators that take parameters but never thought how that worked was very intuitive.
http://stackoverflow.com/questions/739654/understanding-pyth...