[Python-ideas] why is there no decoration for objects

Steven D'Aprano steve at pearwood.info
Fri Aug 21 05:23:38 CEST 2015


On Fri, Aug 21, 2015 at 08:02:14AM +0530, shiva prasanth wrote:

> i think we should add decorators for objects also
> since when you are reviewing the same code
> @increment is easier to understand than
> a=a+1

I don't think it is easier to understand. Look at Stackoverflow or 
Reddit to see how many people ask "what's this funny @foo syntax mean?".

Besides, you can write:

a += 1

which is shorter than either alternative:

# option 1
a = a + 1

# option 2
def increment(x):
    return x + 1

@increment
a


Decorators for functions and classes exist for a very good reason, which 
does not apply to simple variables. For them, just write:

a = decorate(a)

This puts the important thing (the decorator call) right there at the 
assignment. You can't miss it. But with a function or a class:


def func():  # function header
   ...
   code
   more code
   lots of code

func = decorate(func)


the important thing (decorate) is lost, far from the function header. 
Using decorator syntax moves the important call to decorate to the top 
of the function, next to the header.

There's no need for that with simple variables, since a regular function 
call is a one-liner and you can't miss it:

a = decorate(a)



-- 
Steve


More information about the Python-ideas mailing list