开发者

generating exception classes via decorators in python

开发者 https://www.devze.com 2023-02-17 09:24 出处:网络
While coding, I have to do this frequently; class MyClassException(Exception): def __init__(self, _message):

While coding, I have to do this frequently;

class MyClassException(Exception):
    def __init__(self, _message):
        self开发者_StackOverflow中文版.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'
0

精彩评论

暂无评论...
验证码 换一张
取 消