9

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?

Community
  • 1
  • 1
LetMeSOThat4U
  • 6,470
  • 10
  • 53
  • 93

2 Answers2

12

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)
kindall
  • 178,883
  • 35
  • 278
  • 309
  • 4
    Just WTF is cromulent? I thought I knew American language. ;-) Anyway, re this Exception.__init__ thing called last: perfect, but top answer on this issue I linked to does not mention that. thanks! – LetMeSOThat4U Aug 07 '13 at 17:25
  • 5
    "Cromulent" (always preceded by "perfectly") is from *The Simpsons.* "'Embiggens'? I never heard that word before I moved to Springfield." "I don't know why. It's a perfectly cromulent word." Of course, it's debatable whether it actually means "correct" or "acceptable," or is used in an ironic sense to mean the opposite. :-) – kindall Aug 07 '13 at 18:03
  • Cromulent :DDDDD – Igor Pejic May 21 '18 at 17:40
4

This is perfectly safe, you can assign additional attributes on your custom exception instance, as long as it is not .args.

Plenty of custom exception subclasses in the standard library do the same. For example, the urllib2.HTTPError exception adds code, msg, headers, fp and filename attributes.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343