decorators as a special case of an @ operator?

Dan Christensen jdc at uwo.ca
Mon Aug 9 12:44:03 EDT 2004


Peter Hansen <peter at engcorp.com> writes:

> Dan Christensen wrote:
>
>> 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
>
> I think this is identical to the following code, isn't it?
>
>      def f(a, b, c):
>          d = a * b
>          return d + c

Yes.  The anonymity is used below.

> [...]
>> 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.
>
> I think if we asked them, they would clarify that it is not
> the name *alone* which is important, but the *definition*.

Yes, I also feel that way.  Having the function name first isn't the
real merit of my proposal.  The merit (if there is any!) is that you
get a syntax much like the proposed @decorator syntax as a special
case of changes that feel more pythonesque (at least to me).

- anonymous functions are useful in their own right
- @ is just a new binary operator, which reduces punctuation
  (parentheses)

It also allows a form such as

  f = staticmethod @ def (a,b,c):
      d = a * b
      return d + c
    
which is fairly compact, although a little heavy on the
punctuation.

>> - To avoid trailing backslashes, the parser would have to
>>   automatically continue to the next line when a line ends in @.
>
> Sounds like another special case, as I'm not sure Python does
> this for anything right now except when there are matched
> opening and closing symbols.

That's true.  Is there any reason that python doesn't automatically
continue all incomplete binary operators, allowing

   x = a_very_long_expression +
       another_long_expression

?

----

An alternate proposal for 2):  if the parser finds

  f x

where f is callable, interpret this as f(x).  Then the examples
become

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

and

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

But I guess this would introduce some ambiguity into the parser.
Right?

Dan



More information about the Python-list mailing list