在 python 中,一行中的多个“with”语句是否等同于嵌套的“with”语句?
Are multiple `with` statements on one line equivalent to nested `with` statements, in python?
这两个语句等价吗?
with A() as a, B() as b:
# do something
with A() as a:
with B() as b:
# do something
我问是因为 a
和 b
都改变了全局变量(此处为 tensorflow)并且 b
取决于 a
所做的更改。所以我知道第二种形式可以安全使用,但是是否相当于将其缩短为第一种形式?
是的,根据 Python 2.7 language reference:
,在一行中列出多个 with
语句与嵌套它们完全相同
With more than one item, the context managers are processed as if multiple with statements were nested:
with A() as a, B() as b:
suite
is equivalent to
with A() as a:
with B() as b:
suite
完全相同的语言出现在Python 3 language reference。
完全相同。就看个人喜好了。
正如其他人所说,这是相同的结果。下面是有关如何使用此语法的更详细示例:
blah.txt
1
2
3
4
5
我可以打开一个文件并将其内容以简洁的方式写入另一个文件:
with open('blah.txt', 'r') as infile, open('foo.txt', 'w+') as outfile:
for line in infile:
outfile.write(str(line))
foo.txt 现在包含:
1
2
3
4
5
这两个语句等价吗?
with A() as a, B() as b:
# do something
with A() as a:
with B() as b:
# do something
我问是因为 a
和 b
都改变了全局变量(此处为 tensorflow)并且 b
取决于 a
所做的更改。所以我知道第二种形式可以安全使用,但是是否相当于将其缩短为第一种形式?
是的,根据 Python 2.7 language reference:
,在一行中列出多个with
语句与嵌套它们完全相同
With more than one item, the context managers are processed as if multiple with statements were nested:
with A() as a, B() as b: suite
is equivalent to
with A() as a: with B() as b: suite
完全相同的语言出现在Python 3 language reference。
完全相同。就看个人喜好了。
正如其他人所说,这是相同的结果。下面是有关如何使用此语法的更详细示例:
blah.txt
1
2
3
4
5
我可以打开一个文件并将其内容以简洁的方式写入另一个文件:
with open('blah.txt', 'r') as infile, open('foo.txt', 'w+') as outfile:
for line in infile:
outfile.write(str(line))
foo.txt 现在包含:
1
2
3
4
5