[Python-ideas] Keyword same in right hand side of assignments

Terry Reedy tjreedy at udel.edu
Mon Mar 16 21:53:35 CET 2009

Heinrich W Puschmann wrote:
> Python-Ideas: Keyword same in right hand side of assignments
> -------------------------------------------------------------------------------------------
> It is proposed to introduce a Keyword "same", 
> to be used in the right hand side of assignments, as follows: 
>   "xx = same + 5" or "xx = 5 + same"  synonymous with  "xx += 5" 

Only if + is commutative and xx in immutable, and even then, see below.

>   "value =  2*same + 5"  synonymous with "value =*2; value +=5" 
>   "switch = 1 - same"  synonymous with "switch *-1; switch +=1" 
>   "lst = same + [5,6]"  synonymous with  "lst += [5,6]" 
>   "lst = [5,6] + same" synonymous with  "lst = [5,6] + lst" 
>   "lst[2] = 1/same" synonymous with  "lst[2] **=-1" 
> and so on. 

This is an intriguing idea, which seems to extend the idea of augmented 
assignment, and which would seem most useful for complicated target 
expressions or for multiple uses of the pre-existing object bound to the 
target.  It is similar in that the target must have a pre-existing 
binding.  While it might work best for one target, it might not have to 
be so restricted.

But one problem is that it changes and complicates the meaning of 
assignment statements.  Currently,

target-expression(s) = source-expression

means evaluate source-expression; then evaluate target expression (s, 
left to right) and bind it (them) to the source object (or objects 
produce by iterating).  This proposal requires that target be evaluated 
first, resolved to a object, bound to 'same' (or the internal 
equivalent) and after the assignment, unbound from 'same'.

Since targets are expressions and not objects, I believe the target 
expression would have to be re-evaluated (without major change to the 
virtual machine) to make the binding, so this constructions would not 
save a target evaluation and would not be synonymous with augmented 
assignment even if it otherwise would be.  So

lst[2] = 1/same

would really be equivalent to

____ = lst[2]; lst[2] = 1/____; del ____

Another problem is that any new short keyword breaks code and therefore 
needs a strong justification that it will also improve a substantial 
amount of other code.

Terry Jan Reedy

More information about the Python-ideas mailing list