Return value of an assignment statement?

bruno.desthuilliers at gmail.com bruno.desthuilliers at gmail.com
Fri Feb 22 00:24:39 CET 2008


On 21 fév, 23:06, Jeff Schwab <j... at schwabcenter.com> wrote:
> John Henry wrote:
> > On Feb 21, 1:48 pm, John Henry <john106he... at hotmail.com> wrote:
> >> On Feb 21, 1:43 pm, mrstephengross <mrstevegr... at gmail.com> wrote:
>
> >>> Hi all. In C, an assignment statement returns the value assigned. For
> >>> instance:
> >>>   int x
> >>>   int y = (x = 3)
> >>> In the above example, (x=3) returns 3, which is assigned to y.
> >>> In python, as far as I can tell, assignment statements don't return
> >>> anything:
> >>>   y = (x = 3)
> >>> The above example generates a SyntaxError.
> >>> Is this correct? I just want to make sure I've understood the
> >>> semantics.
> >>> Thanks,
> >>> --Steve
> >> That's true, and I am happy that they decided to make that a syntax
> >> error.
>
> > BTW: The less obvious issues when coming from the C world are Python
> > syntax like these:
>
> > y = x = 3
>
> > a = 4
>
> > y = x = a
>
> > print x,y
>
> > a = 5
>
> > print x,y
>
> That's the same behavior I would expect in C, on the grounds that C
> assignments do bit-wise copies.  What I found confusing at first was
> that the same variable will either directly store or merely refer to an
> object, depending on the type of the object:
>
>  >>> a = [ 'hello' ]
>  >>> y = x = a
>  >>> a += [ 'world' ]
>  >>> print x, y
> ['hello', 'world'] ['hello', 'world']

There's nothing like a variable "storing" anything in Python. All you
have are names to (references to) objects binding in a namespace. Now
the fact is that some types are mutable and other are not. In your
above example, the augmented assignment does *not* rebind a, but
invoke a.extend(). With integers, it would have rebind a. So while
your observation is exact, your interpretation is wrong !-)




More information about the Python-list mailing list