[在Python 3.8中具有赋值表达式,为什么我们需要在with中使用as作为?

问题描述 投票:26回答:1

现在PEP 572已被接受,Python 3.8注定具有assignment expressions,因此我们可以在with中使用赋值表达式,即

with (f := open('file.txt')):
    for l in f:
        print(f)

而不是

with open('file.txt') as f:
    for l in f:
        print(f)

它会像以前一样工作。

as关键字与Python 3.8中的with语句有什么用?这是否与Python的Zen背道而驰:“应该有一种-最好只有一种-显而易见的方法。”


[最初提出该功能时,尚没有明确指定是否在with中加上赋值表达式的括号,然后]]

with f := open('file.txt'):
    for l in f:
        print(f)

可以。但是,在Python 3.8a0中,

with f := open('file.txt'):
    for l in f:
        print(f)

将导致

  File "<stdin>", line 1
    with f := open('file.txt'):
           ^
SyntaxError: invalid syntax

但带括号的表达式有效。

现在PEP 572已被接受,Python 3.8注定要具有赋值表达式,因此我们可以在with中使用赋值表达式,即with(f:= open('file.txt')):for f中的l: ...

python python-3.x python-3.8 python-assignment-expression
1个回答
35
投票

TL; DR

© www.soinside.com 2019 - 2024. All rights reserved.