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?
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With