带括号的上下文管理器

Jam*_*ggs 6 python python-3.x python-3.10

我试图了解 Python 3.10 中带括号的新上下文管理器功能的新增功能(此处新功能的顶部项目)。

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

with (open('file1.txt', 'r') as fin, open('file2.txt', 'w') as fout):
    fout.write(fin.read())
Run Code Online (Sandbox Code Playgroud)

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

我的问题是它在Python 3.9.4中也能完美工作吗?

在 Python 3.8.5 中对此进行测试,看起来它不起作用,从而提高了预期的SyntaxError.

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

blu*_*eth 2

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

如果你有这个:

with some_really_long_context_manager(), and_something_else_makes_the_line_too_long():
    pass
Run Code Online (Sandbox Code Playgroud)

你必须这样写,这很难看:

with some_really_long_context_manager(), \
    and_something_else_makes_the_line_too_long():
    pass
Run Code Online (Sandbox Code Playgroud)

如果你的论点太长:

with some_context(and_long_arguments), and_another(now_the_line_is_too_long):
    pass
Run Code Online (Sandbox Code Playgroud)

你可以这样做:

with some_context(and_long_arguments), and_another(
    now_the_line_is_too_long
):
    pass
Run Code Online (Sandbox Code Playgroud)

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

with some_context(and_long_arguments), one_without_arguments(
    ), and_another(now_the_line_is_too_long):
    pass
Run Code Online (Sandbox Code Playgroud)

为此,您必须重新排列:

with some_context(and_long_arguments), and_another(
    now_the_line_is_too_long
), one_without_arguments():
    pass
Run Code Online (Sandbox Code Playgroud)

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

with (
    some_context(and_long_arguments),
    one_without_arguments(), 
    and_another(now_the_line_is_too_long), 
):
    pass
Run Code Online (Sandbox Code Playgroud)

这也使得 diff 更具可读性。