今晚看到v2ex上有人感叹Python没有赋值表达式不方便

本来可以写成:

if result=func1(...):
    print func2(result)

因为没有赋值表达式,所以必须写成:

result=func1(...)
if result:
    print func2(result)

跟帖说了自己的想法:

Scheme/Lua也没有。

赋值语句的返回值为所赋的值,这个我理解起来感觉蛮困难的——我觉得赋值语句应该是没有返回值,或者返回值为nil之类的东西(Haskell里类似赋值的操作返回值的类型是 (),纯副作用的返回值)。

别的语言里,if a == 1,粗心少打一个=号,变成if a = 1就出问题了,但是Python就没这个问题。这一点上比较方便。

真是无巧不成书。前几天刚好看到spine.js有这样一句代码:

listeningToOnce = @listeningToOnce or= []

于是我就手贱给改成了

@listeningToOnce or= []
listeningToOnce = @listeningToOnce

PR 里给的理由是编译出来的js就是赋值表达式:

listeningToOnce = this.listeningToOnce || (this.listeningToOnce = []);

So, (this.listeningToOnce = []) returns the assigned value.

In Scheme/Python/Lua, assignment does not return a value.
This design feels more nature to me.

In some languages assignment returning a value may cause problem in conditions, eg. if a == 1 and if a = 1 (mistype).
Fortunately, in CoffeeScript, we can use is (if a is 1) to avoid this pitfall.


weakish
24.6k 声望844 粉丝

a vigorously lazy deadbeat with matured immaturity