带括号的上下文管理器

2024-05-09

我试图了解新的新内容带括号的上下文管理器Python 3.10 中的功能(新功能中的顶部项目here https://docs.python.org/3.10/whatsnew/3.10.html).

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

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 https://github.com/psf/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

这也使得 diff 更具可读性。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

带括号的上下文管理器 的相关文章

随机推荐