4

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

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

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 中引入的?

4

1 回答 1

0

我不知道这是在,但我很高兴看到它。专业上,我使用了 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

这也使差异更具可读性。

于 2021-06-20T16:12:33.093 回答