说明
数据处理的时候,由于数据乱七八糟的各种原因,很多时候出现各种错误,但是又总不能因为个别错误就影响整个程序的运行,而每个字段都用try-except
的方法又很麻烦,牛逼的程序员都是偷懒的程序员,因此考虑缩写try-except。
问题:如何一句话就可以把try-except的意思表达了?
python里面能一句话表达可能也就是 with语句了,上装饰器的代码:
class IgnoreErrWithDefault(object):
"""shortcuts for exception handling with context method,
and automatically make default value
@usage:
# default value is ""
with ValueErrHandler("") as value:
value = func()
"""
def __init__(self, default_value, throw=False):
# default_values: values
self.default = default_value
self.throw = throw
def __enter__(self):
# print ">>", self.default
return self.default
def __exit__(self, exc_type, exc_value, exc_tb):
if self.throw:
traceback.print_exc()
# return True to ignore the errors, in exc_tb
return not self.throw
用法
def test():
with IgnoreErrWithDefault("default") as value:
raise Exception("error")
value = "valuable"
print value
test()
当然也可以多个值,自行脑补。