0

我一直在玩弄错误处理。特别是用户定义的错误。

但是我不确定以下方法是否是一个坏主意/推荐/很奇怪?

import operator
from functools import partial


class GenericError(Exception):
    def __init__(self, value):
        self.value = value
    def __str__(self):
        return repr(self.value)


def errorhandle(error, func):
    print(func.__name__, "says: ", error)
# or perhaps error_dictionary[error]


def f_test_bool(x, bo, y, et, m, ef):
    """ generic boolean test. If boolean_operator(x,y) == True -->  raise passed in Error """
    try: 
        if bo(x,y):
            raise et(m)
        else:
            return x
    except et as err:
        ef(err, f_test_bool)



partial_ne = partial(f_test_bool, 
                     bo=operator.__ne__, 
                     et=GenericError, 
                     ef=errorhandle)

partial_ne( x = 5, 
            y = 6, 
            m = "oops, 5 is not equal to 6" )




>>> imp.reload(errorhandling)
f_test_bool says:  'oops, 5 is not eqal to 6'

我的想法是,通过这种方式,我可以拥有一个可以重用的简单模块,并通过管道传递值,而无需将用户定义的错误添加到我编写的任何新函数中。我认为这会让事情变得更干净。

4

1 回答 1

1

您为应该简单明了的事情增加了很多开销。不要忘记

简单胜于复杂。

为什么不简单:

if 5 != 6:
   raise ValueError('oops, 5 is not equal to 6')
于 2012-07-11T20:53:56.517 回答