Curious assignment behaviour

Martin von Loewis loewis at informatik.hu-berlin.de
Mon Oct 8 09:04:13 EDT 2001


Dale Strickland-Clark <dale at riverhall.NOSPAMco.uk> writes:

> I'd be much happier if assignment yeilds the value assigned, as it
> does in C (I believe).  It could then be used universaly.
> 
> Also, where is this curious behaviour documented? 6.3 of the Language
> Ref makes no reference to it. (Go on. Prove me wrong!)

Since you're asking for it:

6.3 clearly states that 

x = y = 5     # (1)

is legal syntax; the 

(target_list "=")+

portion matches twice, with the first 'target_list' being 'x', and the
second 'target_list' being 'y'.

It then also explains you what this statement does:

"An assignment statement evaluates the expression list (...) and
assigns the single resulting object to each of the target lists, from
left to right."

So it evaluates the expression first, which gives the value 5,
then assignes it first to x, then to y.

Now, you where asking why

print y = 5        # (2)

is not allowed. This can be answered by looking at the 6.6,

print_stmt:     "print" [ expression ("," expression)* [","] ]

For this statement to be valid, 'y = 5' needs to be an expression.
Looking at 5.10, you'll notice that 'expression' will not allow for
'y = 5', so the code (2) is clearly ill-formed.

In short, assignment is not an expression in Python; that's why it is
listed in statements (section 6), not in expressions (section 5).

You can wish that assignment was an expression. But there are many
good reasons why it shouldn't, backwards-compatibility and less
confusion being among them. On the "less confusion" part: The C
pitfall

   if(x=0)

is enough reason alone not to have assignment as an expression in a
language. The only reason to make assignment an expression in C was to
allow

x = y = 5

but Python achieves this through different means.

Regards,
Martin




More information about the Python-list mailing list