Use cases for "and" in variable assignment

Qua*_*ris 3 python variable-assignment python-3.x

I discovered today that you can use and in variable assignment, similarly to how or is used. I rarely come across using or in this way, but have never even heard of people using and this way. Is this too obscure of a feature to recommend using or are there some concrete use cases where it helps with code clarity or brevity?

a = 1
b = 3
# c is equal to b unless a or b is False; then c is equal to the "False" value. False may be 0, [], False, etc.
c = a and b
print(f'a = {a}, b = {b}, c = {c}')
>>>a = 1, b = 3, c = 3

d = 1
e = 5
# f is equal to d unless d is False; then f is equal to e. Again, "False" may be 0, [], False, etc.
f = d or e
print(f'd = {d}, e = {e}, f = {f}')
>>>d = 1, e = 5, f = 1
Run Code Online (Sandbox Code Playgroud)

There seems to be a weird inconsistency where it's obviously fine to use operators to evaluate a condition and set a variable to the truthiness of that condition (e.g. g = h > i or j = k is l etc).

However, and seems to be an exception. Instead of evaluating the condition right of the assignment, the variable is assigned according to the rule described in the above comment. Why doesn't c = a and b just evaluate to True or False depending on both a and b having truthy values? (The above example would evaluate to True)

Thanks

unp*_*680 6

短路and是用很少的代码表达意图的便捷方法(确实是一个理想的目标)。

考虑一下此初始化,以及user在不为非null的情况下该怎么做。

name = user and user.name
Run Code Online (Sandbox Code Playgroud)

当然,三元将是类似的

name = user.name if user else None
Run Code Online (Sandbox Code Playgroud)

但这可读吗?

最后,当使用短路and方式将多个吸气剂链接在一起时,真正开始节省您的理智。

coords = user and user.location and user.location.coords
Run Code Online (Sandbox Code Playgroud)

使用or提供更好的默认,而不是None当你肯定知道它不会是覆盖一个falsey值的问题。

name = user and user.name or 'Unnamed'
Run Code Online (Sandbox Code Playgroud)