在python中,是否应该在生成器中使用with-语句?需要说明的是,我并不是在询问如何使用装饰器从生成器函数创建上下文管理器。我在问,在生成器中使用with语句作为上下文管理器是否存在固有问题,因为它至少在某些情况下会捕获StopIteration和GeneratorExit异常。下面是两个例子。
Beazley的例子就是这个问题的一个很好的例子(第106页)。我已将其修改为使用with语句,以便在opener方法中的files之后显式关闭文件。我还添加了两种在迭代结果时抛出异常的方法。
import os
import fnmatch
def find_files(topdir, pattern):
for path, dirname, filelist in os.walk(topdir):
for name in filelist:
if fnmatch.fnmatch(name, pattern):
yield os.path.join(path,name)
def opener(filenames):
f = None
for name in filenames:
print "F before open: '%s'" % f
#f = open(name,'r')
with open(name,'r') as f:
print "Fname: %s, F#: %d" % (name, f.fileno())
yield f
print "F after yield: '%s'" % f
def cat(filelist):
for i,f in enumerate(filelist):
if i ==20:
# Cause and exception
f.write('foobar')
for line in f:
yield line
def grep(pattern,lines):
for line in lines:
if pattern in line:
yield line
pylogs = find_files("/var/log","*.log*")
files = opener(pylogs)
lines = cat(files)
pylines = grep("python", lines)
i = 0
for line in pylines:
i +=1
if i == 10:
raise RuntimeError("You're hosed!")
print 'Counted %d lines\n' % i在本例中,上下文管理器成功地关闭了opener函数中的文件。当引发异常时,我会看到异常的跟踪,但生成器会静默地停止。如果with-语句捕捉到异常,为什么生成器不继续?
当我定义自己的上下文管理器在生成器中使用时。我收到运行时错误,说我忽略了一个GeneratorExit。例如:
class CManager(object):
def __enter__(self):
print " __enter__"
return self
def __exit__(self, exctype, value, tb):
print " __exit__; excptype: '%s'; value: '%s'" % (exctype, value)
return True
def foo(n):
for i in xrange(n):
with CManager() as cman:
cman.val = i
yield cman
# Case1
for item in foo(10):
print 'Pass - val: %d' % item.val
# Case2
for item in foo(10):
print 'Fail - val: %d' % item.val
item.not_an_attribute这个小演示在case1中工作得很好,没有引发异常,但在引发属性错误的case2中失败。这里我看到了一个RuntimeException,因为with语句捕获并忽略了一个GeneratorExit异常。
有人能帮我弄清楚这个棘手用例的规则吗?我怀疑这是我正在做的事情,或者在我的__exit__方法中没有做的事情。我尝试添加代码以重新引发GeneratorExit,但没有任何帮助。
发布于 2013-03-12 12:37:40
从Data model entry for object.__exit__
如果提供了异常,并且该方法希望抑制该异常(即阻止其传播),则它应返回一个TRUE值。否则,异常将在退出此方法时正常处理。
在您的__exit__函数中,您将返回True,它将禁止所有异常。如果您将其更改为返回False,异常将继续照常引发(唯一的区别是您保证您的__exit__函数会被调用,并且您可以确保自己清理)。
例如,将代码更改为:
def __exit__(self, exctype, value, tb):
print " __exit__; excptype: '%s'; value: '%s'" % (exctype, value)
if exctype is GeneratorExit:
return False
return True允许您做正确的事情,而不是抑制GeneratorExit。现在,您只能看到属性错误。也许经验法则应该与任何异常处理相同--只有当您知道如何处理异常时,才会拦截它们。有一个__exit__返回的True是一样的(可能会稍微差一点!)比拥有一个裸体更重要,除了:
try:
something()
except: #Uh-Oh
pass请注意,当AttributeError被引发(但未被捕获)时,我认为这会导致生成器对象上的引用计数降至0,然后在生成器中触发GeneratorExit异常,以便它可以自我清理。使用我的__exit__,尝试以下两个案例,希望您能理解我的意思:
try:
for item in foo(10):
print 'Fail - val: %d' % item.val
item.not_an_attribute
except AttributeError:
pass
print "Here" #No reference to the generator left.
#Should see __exit__ before "Here"和
g = foo(10)
try:
for item in g:
print 'Fail - val: %d' % item.val
item.not_an_attribute
except AttributeError:
pass
print "Here"
b = g #keep a reference to prevent the reference counter from cleaning this up.
#Now we see __exit__ *after* "Here"发布于 2013-03-12 12:51:21
class CManager(object):
def __enter__(self):
print " __enter__"
return self
def __exit__(self, exctype, value, tb):
print " __exit__; excptype: '%s'; value: '%s'" % (exctype, value)
if exctype is None:
return
# only re-raise if it's *not* the exception that was
# passed to throw(), because __exit__() must not raise
# an exception unless __exit__() itself failed. But throw()
# has to raise the exception to signal propagation, so this
# fixes the impedance mismatch between the throw() protocol
# and the __exit__() protocol.
#
if sys.exc_info()[1] is not (value or exctype()):
raise https://stackoverflow.com/questions/15353220
复制相似问题