gpt4 book ai didi

多行的 Python 嵌套上下文管理器

转载 作者:IT老高 更新时间:2023-10-28 20:32:47 71 4
gpt4 key购买 nike

在 Python 2.6 中,我们曾经以这种方式格式化我们的嵌套上下文管理器:

with nested(
context1,
context2
) as a, b:
pass

从 Python 2.7 起,nested 已弃用。我已经在一行中看到了很多多个上下文管理器的示例,但是我找不到允许它们在多行上的语法。你会怎么做呢?

# That's working fine
with context1 as a, context2 as b:
pass

# But how do we make it multine?
# These are not working
with (
context1,
context2
) as a, b:
pass

with context1 as a,
context2 as b:
pass

最佳答案

Python 3.10 及更新版本

从 Python 3.10 开始,parentheses are allowed ,你终于可以这样做了:

with (
context1 as a,
context2 as b
):
pass

反斜杠字符

Two or more physical lines may be joined into logical lines usingbackslash characters (\)

(引用 Explicit line joining 部分)

如果您想将上下文管理器放在不同的行上,可以通过以反斜杠结束行来实现:

with context1 as a,\
context2 as b:
pass

contextlib.ExitStack

contextlib.ExitStack是一个

context manager that is designed to make it easy to programmaticallycombine other context managers and cleanup functions, especially thosethat are optional or otherwise driven by input data.

它在 Python 3.3 和更新版本中可用,并且允许轻松输入可变数量的上下文管理器。对于两个上下文管理器,用法如下所示:

from contextlib import ExitStack

with ExitStack() as es:
a = es.enter_context(context1)
b = es.enter_context(context2)

嵌套

可以将上下文表达式拆分为多个 嵌套 with 语句:

With more than one item, the context managers are processed as ifmultiple with statements were nested:

with A() as a, B() as b:

suite is equivalent to

with A() as a:
with B() as b:
suite

(来自 The with statement)

关于多行的 Python 嵌套上下文管理器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31571101/

71 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com