Suf*_*ian 30 python readability exception
有时我发现自己处于需要执行多个顺序命令的情况:
try:
foo(a, b)
except Exception, e:
baz(e)
try:
bar(c, d)
except Exception, e:
baz(e)
...
Run Code Online (Sandbox Code Playgroud)
只需要忽略异常时就会出现相同的模式.
这感觉多余,并且过多的语法使得在阅读代码时难以理解.
在C中,我很容易用宏来解决这类问题,但不幸的是,这不能在直接的python中完成.
问题:在遇到这种模式时,如何才能最好地减少代码占用空间并提高代码可读性?
Rya*_*yan 70
如果你有python 2.5,你可以使用该with语句
from __future__ import with_statement
import contextlib
@contextlib.contextmanager
def handler():
try:
yield
except Exception, e:
baz(e)
Run Code Online (Sandbox Code Playgroud)
您的示例现在变为:
with handler():
foo(a, b)
with handler():
bar(c, d)
Run Code Online (Sandbox Code Playgroud)
Jon*_*nan 14
如果总是这样,当特定函数引发异常时,你总是想要的行为,你可以使用一个装饰器:
def handle_exception(handler):
def decorate(func):
def call_function(*args, **kwargs):
try:
func(*args, **kwargs)
except Exception, e:
handler(e)
return call_function
return decorate
def baz(e):
print(e)
@handle_exception(baz)
def foo(a, b):
return a + b
@handle_exception(baz)
def bar(c, d):
return c.index(d)
Run Code Online (Sandbox Code Playgroud)
用法:
>>> foo(1, '2')
unsupported operand type(s) for +: 'int' and 'str'
>>> bar('steve', 'cheese')
substring not found
Run Code Online (Sandbox Code Playgroud)