decorators as a special case of an @ operator?

Dan Christensen jdc at uwo.ca
Mon Aug 9 10:32:21 EDT 2004


I wonder what people think of the following crazy idea, which has two
parts.

1) Allow anonymous multi-line functions.  For definiteness, I'll use
   the following syntax, but lambda or something else could be used
   too:

   f = def (a,b,c):
         d = a*b
         return d + c

2) Define a *binary* operator @ which is just a shorthand for
   function application:  f @ x = f(x)    

   Note that f(x) is sometimes pronounced "f at x", so @ is a
   reasonable symbol to use.  But it could also be something else.
 
   This @ is not associative;  make the rule that it associates
   from right to left, so   g @ f @ x = g(f(x))

Presto, you have decorators:

f = decorator1 @
    decorator2 @
    def (a,b,c):
        d = a*b
        return d + c

And the function name is at the top, like some people prefer.

Notes:

- Multi-line anonymous functions are something that have been
  requested a lot already.

- With 1) alone, you already can do:

  f = decorator1(
      decorator2(
      def (a,b,c):
          d = a*b
          return d + c
      ))

  The sole purpose of @ is to avoid all the closing parens.

- To avoid trailing backslashes, the parser would have to
  automatically continue to the next line when a line ends in @.

- Since g @ f @ x = g(f(x)), @ is a bit like function composition,
  usually written as a small circle, again suggesting that @ is a
  reasonable symbol.  (But note that g @ f = g(f) which is not the
  same as g composed with f...)

- This @ could be useful in other contexts to avoid deeply
  nested parentheses.

- If x is a tuple, f @ *x could mean f(*x), which allows
  @ to be used with functions of several arguments.  (Not
  very relevant here.)

Dan



More information about the Python-list mailing list