說明
數據處理的時候,由於數據亂七八糟的各種原因,很多時候出現各種錯誤,但是又總不能因爲個別錯誤就影響整個程序的運行,而每個字段都用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()
當然也可以多個值,自行腦補。