gpt4 book ai didi

python - ":="语法和赋值表达式 : what and why?

转载 作者:IT老高 更新时间:2023-10-28 22:15:39 25 4
gpt4 key购买 nike

PEP 572引入了为 Python 3.8 实现的赋值表达式(俗称 Walrus Operator)。这似乎是一个非常重要的新特性,因为它将允许在推导和 lambda 函数中进行这种形式的赋值。

赋值表达式的语法、语义和语法规范究竟是什么?

PEP 379 中的一个类似想法时,为什么要引入这个新的(并且看似非常激进的概念)关于“添加赋值表达式”之前被拒绝过?

最佳答案

PEP 572包含许多细节,尤其是对于第一个问题。我将尝试简明扼要地总结/引用 PEP 的一些最重要的部分:

基本原理

允许在推导中进行这种形式的赋值,例如列表推导和禁止传统赋值的 lambda 函数。这也可以促进交互式调试,而无需重构代码。

推荐的用例示例

a) 获取条件值

例如(在 Python 3 中):

command = input("> ")
while command != "quit":
print("You entered:", command)
command = input("> ")

可以变成:

while (command := input("> ")) != "quit":
print("You entered:", command)

同样,来自 the docs :

In this example, the assignment expression helps avoid calling len()twice:

if (n := len(a)) > 10:
print(f"List is too long ({n} elements, expected <= 10)")

b) 简化列表推导

例如:

stuff = [(lambda y: [y,x/y])(f(x)) for x in range(5)]

可以变成:

stuff = [[y := f(x), x/y] for x in range(5)]

语法和语义

In any context where arbitrary Python expressions can be used, a named expression can appear. This is of the form name := expr where expr is any valid Python expression, and name is an identifier.

The value of such a named expression is the same as the incorporated expression, with the additional side-effect that the target is assigned that value

与常规赋值语句的区别

除了是表达式而不是语句之外,PEP 中还提到了几个不同之处:表达式赋值从右到左,在逗号周围有不同的优先级,并且不支持:

  • 多个目标
x = y = z = 0  # Equivalent: (z := (y := (x := 0)))
  • 分配给一个名字:
# No equivalent
a[i] = x
self.rest = []
  • 可迭代的打包/解包
# Equivalent needs extra parentheses

loc = x, y # Use (loc := (x, y))
info = name, phone, *rest # Use (info := (name, phone, *rest))

# No equivalent

px, py, pz = position
name, phone, email, *other_info = contact
  • 内联类型注解:
# Closest equivalent is "p: Optional[int]" as a separate declaration
p: Optional[int] = None
  • 不支持增强赋值:
total += tax  # Equivalent: (total := total + tax)

关于python - ":="语法和赋值表达式 : what and why?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50297704/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com