我想要这样的行为:
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 theas
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/