【python裝飾器】用with簡單優雅的處理數據錯誤

說明

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

當然也可以多個值,自行腦補。

發佈了4 篇原創文章 · 獲贊 0 · 訪問量 2163
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章