
Understanding Python decorators - ColinWright
http://stackoverflow.com/questions/739654/understanding-python-decorators#1594484
======
krenoten
Learning decorators is usually one of the first 'a-hah!' moments in the
experience of someone coming to python from another language. The wonders of
the yield statement often follow. Here's the obligatory link to 'A Curious
Course on Coroutines and Concurrency' which is an excellent introduction to
one of Python's most unknown yet useful features. As he puts it, they are
similar to 'lightweight classes' that you can use to encapsulate state and
send messages to. In the video, he starts with generators, and eventually ends
up with an entire operating system (scheduler, syscalls, etc...) based on
coroutines.

~~~
jbnicolai
Seems you forgot to include the link, so for those interested:
<http://dabeaz.com/coroutines/>

~~~
krenoten
Ahh yes, thank you!

------
js2
A favorite topic of HN?

[https://www.hnsearch.com/search#request/submissions&q=ti...](https://www.hnsearch.com/search#request/submissions&q=title%3A\(python+decorators\)&sortby=points+desc)

~~~
shill
It's the HN equivalent to Reddit's 'How a Differential Works' video.

[http://www.reddit.com/search?q=differential+works&restri...](http://www.reddit.com/search?q=differential+works&restrict_sr=off&sort=relevance&t=all)

------
themckman
Even as an experience Python developer, I love finding explanations like this.
Sometimes you forget about obscure aspects of a particular feature once you
get in a groove and reading things like this usually makes me think back and
go "Ohh, shoot, if I would've remembered that, I would have built X this
way..." or something similar. This goes for about anything I feel like I
"know".

------
qznc
Decorators by themselves are easy.

    
    
      @foo
      def bar:
        ...
    

is just syntactic sugar for

    
    
      def bar:
        ...
      bar = foo(bar)
    

The hard part is first-class functions and what you can do with them and what
you should not do with them.

~~~
camus
but what about

    
    
        @foo('baz')
        def bar:
    

a bit more complicated to understand imho

~~~
falcolas
Only a little:

    
    
        bar = foo('baz')(bar)
    

[EDIT]: Basically, whatever function is returned from the decorator line (the
function itself, if there is no call, or the results from a function call
otherwise) is applied to the decorated function.

------
jamescun
As a recent convert to Python, I have to say that decorators is one of the
most useful features I have come across thusfar, both syntacticly and
logically.

------
antman
For those who prefer learning by example:
<http://wiki.python.org/moin/PythonDecoratorLibrary>

------
tootie
DRY. DRY DRY DRY.

