带括号的上下文管理器

问题描述

我正在尝试了解 Python 3.10 中新的带括号的上下文管理器功能的新功能(新功能 here 中的顶级项目)。

我的测试示例是尝试编写:

with (open('file1.txt','r') as fin,open('file2.txt','w') as fout):
    fout.write(fin.read())

一个超级简单的测试,它在 Python 3.10 中完美运行。

我的问题是它在 Python 3.9.4 中也能完美运行?

在 Python 3.8.5 中测试这个,它看起来不起作用,提高了预期的 SyntaxError

我是否误解了这个更新,因为这个新语法似乎是在 3.9 中引入的?

解决方法

我不知道这是在,但我很高兴看到它。专业地,我使用了 3.6(没有这个),并且有多个长线上下文管理器和 black,格式化真的很困难:

如果你有这个:

with some_really_long_context_manager(),and_something_else_makes_the_line_too_long():
    pass

你必须写这个丑陋的:

with some_really_long_context_manager(),\
    and_something_else_makes_the_line_too_long():
    pass

如果你的论点太长:

with some_context(and_long_arguments),and_another(now_the_line_is_too_long):
    pass

您可以执行以下操作:

with some_context(and_long_arguments),and_another(
    now_the_line_is_too_long
):
    pass

但是,如果一个上下文管理器不接受参数,这将不起作用,无论如何它看起来有点奇怪:

with some_context(and_long_arguments),one_without_arguments(
    ),and_another(now_the_line_is_too_long):
    pass

为此,您必须重新排列:

with some_context(and_long_arguments),and_another(
    now_the_line_is_too_long
),one_without_arguments():
    pass

使用新语法,这可以格式化为:

with (
    some_context(and_long_arguments),one_without_arguments(),and_another(now_the_line_is_too_long),):
    pass

这也使差异更具可读性。