是否可以将其包装在Python“with”语句中?

时间:2016-01-13 20:44:05

标签: python python-2.7

是否可以使用它来实现以下目标? (使用“with”关键字)

在:

try:
    raise Exception("hello")
except Exception as e:
    print "GOT IT"

期望效果:

def safety():
    try:
        yield
    except Exception as e:
        print "GOT IT"

with safety():
    raise Exception("hello")

它只是使代码更清晰。目前正在运行第二个代码段会出现错误:

Traceback (most recent call last):
  File "testing.py", line 25, in <module>
    with safety():
AttributeError: __exit__

1 个答案:

答案 0 :(得分:7)

你太近了!

from contextlib import contextmanager

@contextmanager
def safety():
    try:
        yield
    except Exception as e:
        print "GOT IT"

with safety():
    raise Exception("hello")