PEP: Adding decorators for everything

Diez B. Roggisch deets at nospam.web.de
Tue Oct 18 19:16:00 CEST 2005


> @GuardedClass
> class Foo:

The functionality can be done using a meta-class, in a similarily 
declarative way.

>     @Transient
>     a = 'a transient field, ignored when serializing'
> 
>     @Const
>     PI = 22.0 / 7
> 
>     @TypeSafe(int)
>     count = 10

These are tricky, as the implicitly change the nature of the values - 
they become properties. And the decorator protocol has to change, as the 
passed value is obviously not a callable, but a random value. So in the 
end, you could simply do something like this:


@Const(3.24)
def PI(self):
    pass

with Const basically ignoring its callable-argument and simply returning 
a get-only-property. I have to admit that I was tempted to use such a 
thingy just the other day. But it is not exactly nice, and using

PI = Const(3.14) as you suggested is even more pleasing.

Additionally, the first @Transient-decorator can't be done that way, as 
the decorator protocol doesn't know about the _name_ a thing is bound to 
later. And you'd need that to actually set up e.g. __getstate__ operate 
properly.

And it doesn't mkae much sense anyway, as "a" is a class variable, not a 
instance variable.

So - I'm not very much in favour of these enhancements.


> It would also be better if multiple decorators could be written on the
> same line. E.g.:
> @A @B(x, y) @C
> def foo(): ...

That one I like.

Diez



More information about the Python-list mailing list