[Python-ideas] Decorators for variables

Steven D'Aprano steve at pearwood.info
Sat Apr 2 23:09:21 EDT 2016


On Fri, Apr 01, 2016 at 07:44:21PM +0200, Michel Desmoulin wrote:

> Not saying I like the proposal, but you can argue against regular
> decorators the same way:
> 
> @foo
> def bar():
>    pass
> 
> Is just:
> 
> bar = foo(bar)


Not quite. It's actually:

def bar():
    pass
bar = foo(bar)

which is *three* uses of the same name, two of which may be a long way 
from the first. As you say:

> But, I think the benefit for @decorator on functions is mainly because a
> function body is big, 

That is certainly part of the justification for @ syntax.

It might help to remember that decorators themselves have been possible 
in Python going all the way back to Python 1.5, at least, if not 
earlier, and the first three decorators in the standard library 
(property, classmethod and staticmethod) were added a few releases 
before decorator syntax using @. (If I remember correctly, property etc 
were added in 2.2 but @ syntax wasn't added until 2.4.)

So the decorator concept had many years to prove itself before being 
given special syntax. The two reasons for adding extra syntax were:

(1) to keep the decoration near the function declaration; and

(2) to avoid having to repeat the function name three times.


> and this way we can read the decorator next to the
> function signature while on a variable, this just add another way to
> call a function on a variable.

I'm afraid I don't understand what you mean by this. What does "while on 
a variable" mean here?



-- 
Steve


More information about the Python-ideas mailing list