Question

I have been playing around with using error handling. In particular with user defined errors.

However I am not sure if the following approach a bad idea / recommended / plain weird?

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'

my thought was that this way, I could have a simple module that I can re-use, and pipe values through without having to add user-defined errors to any new functions that I write. I thought this would keep things cleaner.

Was it helpful?

Solution

You're adding a lot of overhead for something that should be simple and obvious. Don't forget the zen:

Simple is better than complex.

Why not simply:

if 5 != 6:
   raise ValueError('oops, 5 is not equal to 6')
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top