Welcome, guest | Sign In | My Account | Store | Cart

an Exception base-class that supports keyword arguments and pretty printing

Python, 41 lines
 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.

3 comments

Ori Peleg 15 years, 7 months ago  # | flag

cool! I love it.

Christopher Dunn 15 years, 5 months ago  # | flag

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.

Created by tomer filiba on Sat, 13 May 2006 (PSF)
Python recipes (4591)
tomer filiba's recipes (12)

Required Modules

  • (none specified)

Other Information and Tasks