Python 可迭代和上下文管理器

标签 python contextmanager

我想要这样的行为:

with A() as f:
    for x in f:
        do_something(f)

这是正确的做法吗?

class A:
    def __enter__(self):
        print "Entering context"

    def __iter__(self):
        for x in ["some","list"]:
            yield x

    def __exit__(self):
        print "Deleting context"

最佳答案

您的contextmanager.__enter__ 方法需要返回可迭代对象。它可以self:

def __enter__(self):
    print "Entering context"
    return self

参见 With Statement Context Managers documentation :

object.__enter__(self)

Enter the runtime context related to this object. The with statement will bind this method’s return value to the target(s) specified in the as clause of the statement, if any.

因此无论方法返回什么,都将绑定(bind)到作为 as 目标给出的名称。

你的 contextmanager.__exit__ method如果出现异常,则需要能够接受异常:

def __exit__(self, exc_type, exc_value, traceback):

如果没有异常,with 语句会为您提供三个 None 参数。

关于Python 可迭代和上下文管理器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26475443/

相关文章:

python - 如何嵌套任意数量的 Python 文件上下文管理器?

python - 在 python 上下文管理器中返回 finally block

python - 有没有办法在正则表达式 python 中检查同一字符串中的两种不同模式?

python - 无法在简单数据集上训练 Tensorflow

python - 使用 GeoDjango 获取相关位置字段

python - 为什么上下文管理器不关闭文件描述符?

python-3.x - 如何在多个异常情况下使用 pytest.raises?

python - 使用 Numpy 在 Python 中处理图像

python - 如何使用 Google Colab 本地运行时并连接到 Google Drive

python - Python 中上下文管理器和装饰器的区别