Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom exceptions with kwargs (Python)

Is this safe?

class SpecialAlert(Exception):

    def __init__(self, message, **kwargs):
        Exception.__init__(self, message)
        for kw in kwargs:
            if kw == 'message':
                continue
            setattr(self, kw, kwargs[kw])

Related to: Proper way to declare custom exceptions in modern Python?

Butt.. Is this safe? I mean I'm overriding attributes of self?

In SpecialAlert I want to pass all kinds of things (this is an exception done for doing a long series of different checks, I do "try..except SpecialAlert as error" in a loop and then get details out of error in handlers)

I have a basic check if I'm not overriding "message", should I skip setting other attrs on self too? What are they?

like image 586
LetMeSOThat4U Avatar asked Aug 07 '13 16:08

LetMeSOThat4U


1 Answers

This will work fine; it's perfectly cromulent to put additional attributes on an object. However, rather than checking specifically for standard attributes you don't want to clobber, just call Exception.__init__ last, and let it clobber yours if you accidentally set them. Then your __init__() can just be:

def __init__(self, message, **kwargs):
    self.__dict__.update(kwargs)
    Exception.__init__(self, message)
like image 66
kindall Avatar answered Sep 24 '22 14:09

kindall