像这样:
import sys
class Context(object):
def __enter__(self):
try:
raise Exception("Oops in __enter__")
except:
# Swallow exception if __exit__ returns a True value
if self.__exit__(*sys.exc_info()):
pass
else:
raise
def __exit__(self, e_typ, e_val, trcbak):
print "Now it's running"
with Context():
pass
为了使程序以一种愉快的方式继续运行而不执行上下文块,您需要检查上下文块内的上下文对象,并且仅在__enter__
成功后才做重要的事情。
class Context(object):
def __init__(self):
self.enter_ok = True
def __enter__(self):
try:
raise Exception("Oops in __enter__")
except:
if self.__exit__(*sys.exc_info()):
self.enter_ok = False
else:
raise
return self
def __exit__(self, e_typ, e_val, trcbak):
print "Now this runs twice"
return True
with Context() as c:
if c.enter_ok:
print "Only runs if enter succeeded"
print "Execution continues"
据我所知,您不能完全跳过with块。并请注意,此上下文现在吞没了其中的 所有 异常。如果您不希望吞下异常(如果__enter__
成功),请签self.enter_ok
入__exit__
,return False
如果是True
。