a = b = 1 just syntactic sugar?

Robin Munn rmunn at pobox.com
Wed Jun 4 11:45:17 EDT 2003


Robin Munn <rmunn at pobox.com> wrote:
>=== Begin Python transcript ===
>>>> a = b = []
>>>> a
> []
>>>> b
> []
>>>> id(a)
> 135714444
>>>> id(b)
> 135714444
>>>> a is b
> 1
>>>> a = []
>>>> b = []
>>>> id(a)
> 135714732
>>>> id(b)
> 135714508
>>>> a is b
> 0
>==== End Python transcript ====

This got me curious. I know that in the "1<i<10" syntax, the expression
in the middle (i) is only evaluated once, which can be important for
(say) functions with side-effects. But in assignment, how many times is
the RHS evaluated?

=== Begin Python transcript ===
>>> def foo():
...     print "Side effect!"
...     return 5
...
>>> a = b = foo()
Side effect!
>>> a
5
>>> b
5
==== End Python transcript ====

It seems the RHS is only evaluated once in chained assignment, at least
as of Python 2.2.2.

-- 
Robin Munn <rmunn at pobox.com>
http://www.rmunn.com/
PGP key ID: 0x6AFB6838    50FF 2478 CFFB 081A 8338  54F7 845D ACFD 6AFB 6838




More information about the Python-list mailing list