[Python-ideas] Assignment decorators (Re: The Descriptor Protocol...)

Steven D'Aprano steve at pearwood.info
Tue Mar 8 22:43:41 CET 2011

Larry Hastings wrote:
> On 03/07/2011 10:50 PM, Raymond Hettinger wrote:
>> Just for the fun of it, here's my offering:
>>      a := gizmo(arg1, arg2)
>> is equivalent to
>>      a = gimzo(arg1, arg2, __name__='a')
> How do you call two assignment decorators with this syntax?

The obvious way:

a, b := gizmo(arg1, arg2), widget(arg3)
# a, b = gimzo(arg1, arg2, __name__='a'), widget(arg3, __name__='b')

A more important question, what happens if we do this?

a := obj

>> Advantages:
>>    * Keep the current '@' notation unambiguous
> I don't think any of the proposed annotation syntaxes have been ambiguous.

Perhaps ambiguous is the wrong word, but it certainly overloads the 
meaning of @ and gives it a second, quite different meaning. So much so 
that I claim that "assignment decorator" is completely the wrong term to 
use to describe it. The feature we're discussing is not an enhanced form 
of decoration, it is an enhanced form of *assignment*. I think Raymond 
has got it right, the only appropriate syntax is a variation of the 
assignment syntax.

In current Python, decoration refers to the idiom:

x = something
x = decorator(x)

Before the @ syntax was available, we still used decorators like this:

def x():

x = decorator(x)

Notice that it's the *def* that gives the magic "knows its own name" 
behaviour, not the decorator. The decorator is just a function. You can 
decorate objects that aren't functions or classes, just without the 
advantage of nice syntax. Critical to the idea of decoration is that the 
decorator function is a function that wraps or otherwise modifies an 
existing object.

The proposed behaviour is nothing like decoration. It doesn't wrap an 
existing object, but changes the compiler's behaviour when creating it 
in the first place. What is fundamental to this proposed functionality 
is the idea of the right hand side of assignment being aware of the name 
  which is the target of that assignment. There are currently three 
things which already do this:

* defining a class and assigning it to a name using the class keyword
* defining a function and assigning it to a name using the def keyword
* applying a decorator using the @ syntax

What these three things have in common is *assignment*, not decoration.


More information about the Python-ideas mailing list