现在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: ...
TL; DR