A decorator syntax not yet mentioned (I think!)

Peter Hansen peter at engcorp.com
Wed Aug 11 11:40:32 EDT 2004


John Marshall wrote:
> How about the following, which I am almost positive
> has not been suggested:
> -----
> class Klass:
>     def __init__(self, name):
>         self.name = name
> 
>     deco meth0:
>         staticmethod
>     def meth0(x):
>         return x
> 
> -----
> 1) The decorators clearly apply to a specific method/function,
>    therefore there is no need to do any stack pushing in memory
>    until the method/function definition is done.

Problems with that: duplication (since you now have the name
of the function in two places) and readability (it's harder to
see the "def" because the name you picked is too close to it
in length and appearance).

On the other hand, there's no need to have the function name
there (was anyone complaining about "stack pushing"?), so
maybe just using "decorate" would be okay, or a different
keyword:

class Klass:
     # init set

     decorate:
         staticmethod
     def meth0(x):
         return x

> 2) The decorators are "outside" of the method/function they
>    decorate:
>    a) which will please those who want the outside location
>    b) will not be folded within the function
>    c) folding on the decorators can be done so that the
>       def is not obfuscated
>    d) can be located anywhere in the code--but most likely
>       before the "def ...()"
> 3) The sequence in which the decorators are applied is just
>    like code would be--this is certainly intuitive given
>    that we are writing code.

> Any comments?

Has potential, I think, with some changes.

I like the following about it:

1) keyword instead of punctuation
2) indentation consistent with rest of Python
3) similarity to try/finally or while/else and friends where
    the two clauses are coupled

I wouldn't mind seeing exactly the same idea allowed for
decorators *inside* the function as well, so that we can
experiment for a while and see which, if any, is preferred,
but I doubt that would happen.

-Peter



More information about the Python-list mailing list