Wednesday, November 19, 2014

assignment order

Variable assignment in a chained "=" goes left-to-right.

>>> a = [None]
>>> a[0][0] = a  # fails, as expected
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'NoneType' object has no attribute '__getitem__'
>>> a[0] = a[0][0] = a  # succeeds

The second form is equivalent to:
>>> a[0] = a
>>> a[0][0] = a

With a bit of code we can explicitly see that the assignments are happening in left-to-right order:

>>> class Squawker(object):
...    def __init__(self, name): self.name = name
...    def __setitem__(self, key, val): print self.name
...
>>> Squawker("a")[0] = Squawker("b")[0] = 1
a
b

1 comment:

  1. Yeah, Of course, it is With a bit of code we can explicitly see that the assignments are happening in left-to-right order. Anyway, I'm looking for an Harvard referencing style If anyone can tell me about it.

    ReplyDelete