2

An example of what the title talks about:

#seen in a demo of PyOpenGL
# http://PyOpenGL.sourceforge.net/
size = self.size = self.GetClientSize()

What is this used for? How does it works and when using it?

My idea is this allows to assign the value of the third item to the first and the second... If that's it, we can nest an infinite number of vars.

1

3 Answers 3

8

It is a chained assignment. You set both size and self.size to the return value of self.GetClientSize().

You can chain assignments with abandon:

>>> foo = bar = spam = eggs = 'frobnicators'
>>> foo
'frobnicators'
>>> bar, spam, eggs
('frobnicators', 'frobnicators', 'frobnicators')

Note that the expression on the right-hand side only is evaluated once, and it's value is assigned to all the left-hand side variables from left to right.

This can most easily be seen if you decompiled the python bytecode:

>>> import dis
>>> def foo():
...     bar = baz = eggs = 'spam'
... 
>>> dis.dis(foo)
  2           0 LOAD_CONST               1 ('spam')
              3 DUP_TOP             
              4 STORE_FAST               0 (bar)
              7 DUP_TOP             
              8 STORE_FAST               1 (baz)
             11 STORE_FAST               2 (eggs)
             14 LOAD_CONST               0 (None)
             17 RETURN_VALUE        

DUP_TOP creates an extra reference to the value on the stack (spam), which is stored in bar, then baz is given another duplicated reference, then the value is stored in eggs.

Sign up to request clarification or add additional context in comments.

2 Comments

Looks pretty neat now, using dis to explain it is a good idea.
Surprisingly, the assignment proceeds left to right, not right to left.
0

When you want to assign the value on RHS to two variables in the same statement..

a = b = 2

Both a and b contains 2..

This can be used when you want to create an alias for your variable, you just assigned value to, because may be you want to use that value in two different ways..

Comments

0

It is roughly equivalent to

temp=self.GetClientSize()
size=temp
self.size=temp
del temp

But it executes faster and is generally easier to read than this form. Note that it is not the same as

self.size=self.GetClientSize()
size=self.getClientSize()

which executes self.getClientSize() 2 times, nor the same as

self.size=self.GetClientSize()
size=self.size

observe

class test(object):
    def setter(self, val):
        self._t=val
    def getter(self):
        return 5
    t=property(fget=getter,fset=setter)

a=test()
b=a.t=9
print a.t, b

prints 5 9

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.