Decorator

bruno at modulix onurb at xiludom.gro
Fri May 12 13:47:10 EDT 2006


Martin Blume wrote:
> "Sybren Stuvel" schrieb
> 
>>Martin Blume enlightened us with:
> 
> Don't know if I enlightened anybody ... :-)

Not sure...

But let's hope someone else having doubts about @decorator will find
this thread, so we won't have to point him/her to the documentation.

>>>Another question: Isn't decorating / wrapping
>>> usually done at runtime, so that the @deco 
>>>notation is pretty useless (because you'd
>>>have to change the original code)?
>>
>>Please explain why that would make the @deco 
>>notation pretty useless.
>>
> 
> Well, if you're changing the original module,

Who's talking about "changing the original module" ?

> you
> might as well insert the needed functionality in
> the original function, no?

higher order functions allow to keep orthogonal responsabilities
separated.

(snip)

> Isn't the point of a decorator to change the 
> behavior externally, at runtime, possibly changing
> it in different ways at different places at different
> times?

You're confusing the python specific @decorator syntax with the OO
design pattern by the same name. This syntax is purely syntactic sugar
for a specific use case of higher order functions.

> So why this @deco notation? 

To improve readability.

@decorator
def my_one_hundred_locs_func():
  ...

is much more readable than:
def my_one_hundred_locs_func():
  ...
  # 100 LOCS later
my_one_hundred_locs_func = decorator(my_one_hundred_locs_func)

> Can you apply it externally?

No. It doesn't make sens to replace:
  mymodule.func = decorator(mymodule.myfunc)
with
  @decorator
  mymodule.func

Note that all this should be clear for anyone having read the doc...

HTH
-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'onurb at xiludom.gro'.split('@')])"



More information about the Python-list mailing list