python海象运算符

官网介绍:Assignment expressions(赋值表达式)
There is new syntax := that assigns values to variables as part of a larger expression. It is affectionately known as “the walrus operator” due to its resemblance to the eyes and tusks of a walrus.
表达式的一部分赋值给变量

使用

示例1:

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

使用海象运算符后,可以改写成以下形式:

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

示例2:

1
2
3
# Loop over fixed length blocks
while (block := f.read(256)) != '':
process(block)
------------- The End -------------