上下文管理器 运行 可以在 Python 中多次包含块吗?
Can Context Managers run the included block multiple times in Python?
作为一个基本示例,假设如下:
with runFiveTimes:
print("test")
这在 Python 中可行吗?
(这个例子只是为了澄清问题,显然有更简单的方法来实现这个具体的例子)
这不可能。我试图向上下文管理器添加多个 yield 语句,Python 不合适。 解决了更多问题,并解释了一些不错的选择。
This guy examined the bytecode produced, and found that this is not possible. (This guide 解释了每个字节码的含义。)
并且 this guy 表明上下文管理器存储在堆上,这是 类 所在的位置,而不是对象。
作为一个基本示例,假设如下:
with runFiveTimes:
print("test")
这在 Python 中可行吗?
(这个例子只是为了澄清问题,显然有更简单的方法来实现这个具体的例子)
这不可能。我试图向上下文管理器添加多个 yield 语句,Python 不合适。
This guy examined the bytecode produced, and found that this is not possible. (This guide 解释了每个字节码的含义。)
并且 this guy 表明上下文管理器存储在堆上,这是 类 所在的位置,而不是对象。