简体   繁体   English

Python可迭代和上下文管理器

[英]Python iterable and context manager

I want behaviour as such: 我想要这样的行为:

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

is this the right way to do it? 这是正确的方法吗?

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

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

    def __exit__(self):
        print "Deleting context"

Your contextmanager.__enter__ method needs to return the iterable. 您的contextmanager.__enter__方法需要返回可迭代的。 It can be self : 可以self

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

See the With Statement Context Managers documentation : 请参阅With Statement Context Managers文档

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. with语句会将此方法的返回值绑定到该语句的as子句中指定的目标(如果有)。

so whatever the method returns is then bound to the name given as the as target. 因此,无论该方法返回什么,都将绑定到作为as目标给出的名称。

Your contextmanager.__exit__ method needs to be able to accept the exception if one was raised: 如果引发了异常,您的contextmanager.__exit__方法需要能够接受该异常:

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

When there is no exception, the with statement gives you three None arguments. 没有例外时, with语句为您提供三个None参数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM