a = b = 1 just syntactic sugar?

sismex01 at hebmex.com sismex01 at hebmex.com
Tue Jun 3 14:43:27 EDT 2003


> 
> Batista, Facundo wrote:
> > "b = 1" does not return 1, just returns b. a and b are the 
> > same object now (they are not just equal, they are the very same).
> 
> if b = 1 returns b, then why can't you say  a = (b = 1)  ?
>

Don't "think in another language", think in Python.

"b=1" returns nothing, because it's a statement, not
an expression.  It's easy to see with eval(), which
is used to evaluate expressions and it returns it's
result:

Python 2.2 (#28, Dec 21 2001, 12:21:22) [MSC 32 bit (Intel)] on win32
Type "copyright", "credits" or "license" for more information.
IDLE 0.8 -- press F1 for help
>>> eval("1")
1
>>> eval("b=1")
Traceback (most recent call last):
  File "<pyshell#2>", line 1, in ?
    eval("b=1")
  File "<string>", line 1
    b=1
     ^
SyntaxError: invalid syntax


So, as you can see, "b=1" is not an expression that
"returns" b, it's a statement that assigns to the
name "b" a reference to the int() object "1".

When the compiler sees "a = b = 1", what it does is
multiple assignments of the same object (after the
last "=") to all the names it finds.


HTH.

-gca
Advertencia:La informacion contenida en este mensaje es confidencial y
restringida, por lo tanto esta destinada unicamente para el uso de la
persona arriba indicada, se le notifica que esta prohibida la difusion de
este mensaje. Si ha recibido este mensaje por error, o si hay problemas en
la transmision, favor de comunicarse con el remitente. Gracias.





More information about the Python-list mailing list