简体   繁体   中英

generating exception classes via decorators in python

While coding, I have to do this frequently;

class MyClassException(Exception):
    def __init__(self, _message):
        self.message = _message

class MyClass(object):
    def __init__(self, value):
        raise MyClassException("What's up?")

It'd be nice to be able to have my Exception classes via a decorator call, since all those dummy classes all inherited from Exception have nothing unique but name. The following would be great for instance;

 @generic_exception_class
 class MyClass(object):
    def __init__(self, value):
        raise MyClassException("What's up?")

Since there's no way to make MyClassException present until the decorator is called it'd give me syntax name error no matter what. Is there a way to do this in python in any similar way?

Here's one possibility. Note that the exception class will be a member of the decorated class, it is not at global scope.

# The decorator
def class_with_exception(cls):
    def init(self, _message=''):
        self.message = _message
    excname = 'ClsException'
    excclass = type(excname, (Exception,), {'__init__': init})
    setattr(cls, excname, excclass)
    return cls

# example usage
@class_with_exception
class MyClass(object):
    def __init__(self):
        raise MyClass.ClsException('my message')

# raises and catches exception
try:
    MyClass()
except MyClass.ClsException:
    print 'catching exception'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM