# PEP572: 海象运算符

### 海象运算符

PEP572的标题是「Assignment Expressions」，也就是「赋值表达式」，也叫做「命名表达式」，不过它现在被广泛的别名是「海象运算符」(The Walrus Operator)。因为 :=

### 语法和语义

#### 赋值给中间变量

pattern = re.compile('s')
data = 'ss'
if pattern.match(data):
print(pattern.match(data).group(0))

。正确的写法是：

match = pattern.match(data)
if match:
print(match.group(0))

if (match := pattern.match(data)) is not None:
print(match.group(0))

pattern.match(data)


while 1:
if not line:
break
print(line)

while (line := fp.readline()):
print(line)

#### 简化列表解析

results = []
for x in data:
result = f(x)
if result:
results.append(result)

results = [
f(x) for x in data
if f(x)
]

results = [
y for x in data
if (y := f(x))
]

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

### Golang里面的:=

:=

(Short variable declarations)语法:

// ShortVarDecl = IdentifierList ":=" ExpressionList .
i, j := 0, 10
f := func() int { return 7 }

func f(n int) (res int, err error) {
if _, err := f(n-1); err != nil {
return
}
return
}

:=

### 我对PEP 572的看法

Dustin Ingram在PyCON2019上做了一个《PEP 572: The Walrus Operator》的分享，最后他也说自己不喜欢这个语法，但是他接着说：

You might say well i don't like it, that's totally fine. you don't have to like it if you don't like it then don't write it