decorators - more than just syntactic sugar

Duncan Booth duncan.booth at invalid.invalid
Mon Aug 13 07:47:28 EDT 2007


Marc 'BlackJack' Rintsch <bj_666 at gmx.net> wrote:

> On Sat, 11 Aug 2007 20:30:54 +0200, Helmut Jarausch wrote:
> 
>> are decorators more than just syntactic sugar in python 2.x and what
>> about python 3k ?
> 
> They are just syntactic sugar.
> 
> @spam
> def ham():
>     pass
> 
> is the same as
> 
> def ham():
>     pass
> 
> ham = spam(ham)

Decorators are almost just syntactic sugar, but in fact there is a subtle 
difference between the two bits of code you gave: in the second one you 
assign the function to the name ham and then replace it with the result of 
calling spam. With the decorator syntax you only have one assignment to ham 
and when that decorator is called that assignment has not yet happened.

The difference is small, but you can write decorators which depend on it. 
For example, the code I posted in <Xns998998BD9112Fduncanbooth at 127.0.0.1> 
depends on this difference and will not work if you write the calls out 
explicitly instead of using decorators.





More information about the Python-list mailing list