python的chained assignment

python小知识关于a=b=True是怎样工作的

链式赋值关于python有一个有趣的地方,从上面这段话我们可以了解到:

1、在C语言中,a=b=True等价于

1
2
b = True
a = b

2、而在python中,a = b = True等价于

1
2
3
4
temporary_expr_result = True
a = temporary_expr_result
b = temporary_expr_result

下面是wikipedia的说明,

In some programming languages (C for example), chained assignments are supported because assignments are expressions, and have values.In this case chain assignment can be implemented by having a right-associative assignment, and assignments happen right-to-left. For example, i = arr[i] = f() is equivalent to arr[i] = f(); i = arr[i]. In C++ they are also available for values of class types by declaringthe appropriate return type for the assignment operator.

In Python, assignment statements are not expressions and thus do not have a value. Instead, chained assignments are a series of statements with multiple targets for a single expression. The assignments are executed left-to-right so that i = arr[i] = f() evaluates the expression f(), then assigns the result to the leftmost target, i, and then assigns the same result to the next target, arr[i], using the new value of i.[9] This is essentially equivalent to tmp = f(); i = tmp; arr[i] = tmp though no actual variable is produced for the temporary value.
Chained assignment

那么问题来了,如果赋值的这个RHS(右值)是可变类型的,比如是一个list、dict,当我们希望a = b = [],a, b分别得到不同的list时显然出错了。
另一个简单的说明例子:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
>>> def somefunction():
... return []
...
>>> x = y = somefunction()
>>> x.append(4)
>>> x
[4]
>>> y
[4]
>>> x = somefunction(); y = somefunction()
>>> x.append(3)
>>> x
[3]
>>> y
[]

这是Python最常见的坑之一,更多讨论请看这里

另外一点:关于chaining operators

在python中 a is b is c 等价于 a is b and b is c
所以,猜猜
False is False is False
的结果是什么?
参考

http://en.wikipedia.org/wiki/Assignment_%28computer_science%29#Chained_assignment
http://stackoverflow.com/questions/11498441/what-is-this-kind-of-assignment-in-python-called-a-b-true
http://stackoverflow.com/questions/7601823/how-do-chained-assignments-work
http://www.tutorialspoint.com/python/python_variable_types.htm