an Exception base-class that supports keyword arguments and pretty printing
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 | class ExceptionContainer(Exception):
def __init__(self, message = "", **kw):
self.__dict__["__info"] = Container(message = message, **kw)
def __delattr__(self, name):
delattr(self.__dict__["__info"], name)
def __getattr__(self, name):
return getattr(self.__dict__["__info"], name)
def __setattr__(self, name, value):
setattr(self.__dict__["__info"], name, value)
def __repr__(self):
return repr(self.__dict__["__info"])
def __str__(self):
return str(self.__dict__["__info"])
---------
example:
---------
>>> class FileNotFoundError(ExceptionContainer):
... pass
...
>>> raise FileNotFoundError("failed to open the file!", filename = "/tmp/blah", errno = 17)
Traceback (most recent call last):
File "<stdin>", line 1, in ?
__main__.FileNotFoundError: Container:
errno = 17
filename = '/tmp/blah'
message = 'failed to open the file!'
>>>
>>> try:
... raise FileNotFoundError("failed to open the file!", filename = "/tmp/blah", errno = 17)
... except FileNotFoundError, ex:
... ex.errno = 18
... raise
...
Traceback (most recent call last):
File "<stdin>", line 2, in ?
__main__.FileNotFoundError: Container:
errno = 18
filename = '/tmp/blah'
message = 'failed to open the file!'
>>>
|
!! requires the Conatiner class from my Container's recipe !!
finally, you can throw exceptions with keyword arguments. no more ugly tuple unpacking.
Tags: extending
cool! I love it.
the Container recipe (link). http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/496697
Wrong category. Interesting, but this is in the wrong category. "Extending" refers to loading symbols into the Python interpretter, via either a dynamic library or recompiling the interpretter itself.
Extending the Exception class would go under "Object Oriented", maybe.