我能得到的最接近的是使用两个嵌套的上下文管理器,像下面这样:
class SkippedException(Exception):
pass
class SkipContext:
def __enter__(self):
pass
def __exit__(self, type, value, tb):
return type is SkippedException
class SomeContext:
def __init__(self, arg):
self.arg = arg
def __enter__(self):
if self.arg == 1:
print "arg", self.arg
raise SkippedException()
def __exit__(self, type, value, tb):
pass
with SkipContext(), SomeContext(1):
print "body"
的SkipContext
经理基本上是抓住由内SomeContext
经理的情况下提出的,其中arg == 1
的SkippedException
。
请注意,多个上下文表达式的语法仅在Python 2.7或更高版本中受支持。在早期版本中,你会写:
with SkipContext():
with SomeContext(1):
print "body"
的contextlib.nested
上下文管理器,尽管文件要求,不完全匹配上述嵌套with
语句的语义异常时,从__enter__
内抛出,所以它在这种情况下不起作用。
应该指出,PEP 343提到隐藏流量控制的宏(如上下文管理器)应该不鼓励,并且引用Raymond Chen's rant against hidden flow control。
它不起作用并引发异常。我甚至尝试用一个除了所有例外的包装器包装。然后它抛出一个'AttributeError:__exit__'错误。 –