<pre><code>def fn_with_long_name(n):
return n
def case_1():
if (x := fn_with_long_name(2)) == 2:
print("a", x)
else:
print("b", x)
# 什么?这里多了个变量 x ?
def case_2():
x = 100
if (x := fn_with_long_name(2)) == 2:
print("a", x)
else:
print("b", x)
# 啊? x 在上面哪改了
assert x != 100
def case_3():
x = fn_with_long_name(3)
if x == 2:
print("a", x)
else:
print("b", x)
</code></pre>
<p>我觉得声明变量藏在条件语句中,这也太难找了吧, 一不留神多了个变量;更怕覆盖了之前的值,因为这种写法让我以为声明的变量的作用域是 if 块。 所以我的暴论是:我各种情况下一概不用,也不看它的适用场景了;毕竟 python zen 中说:</p>
<ul>
<li>Explicit is better than implicit.</li>
<li>Special cases aren't special enough to break the rules.</li>
<li>There should be one-- and preferably only one --obvious way to do it.</li>
</ul>