On Tue, 11 Dec 2007 12:51:52 -0800, Nishkar Grover wrote:
I'm trying to replace a built-in exception type and here's a simplified
example of what I was hoping to do...
>>import exceptions, __builtin__
>>>
>>zeroDivisionError = exceptions.ZeroDivisionError
I don't know why you're fiddling that much with the names,
`ZeroDivisionError` is a builtin name. If you do this to avoid
overwriting the base classes, consider the following example::
>>class A(object): pass
...
>>class B(A): pass
...
>>A_backup = A
A_backup is A
True
>>class A(object): pass
...
>>A_backup is A
False
>>B.__base__ is A
False
>>B.__base__ is A_backup
True
The names really just point to an object. Once the resolution from a name
to a real object is done, you can reuse the name.
>>class Foo(zeroDivisionError):
... bar = 'bar'
...
>>>
>>exceptions.ZeroDivisionError = Foo
>>ZeroDivisionError = Foo
>>__builtin__.ZeroDivisionError = Foo
>>>
>>try:
... raise ZeroDivisionError
... except ZeroDivisionError, e:
... print e.bar
...
bar
>>>
>>try:
... 1/0
... except ZeroDivisionError, e:
... print e.bar
...
Traceback (most recent call last):
File "<stdin>", line 2, in ?
ZeroDivisionError: integer division or modulo by zero
>>>
>>>
The object that ZeroDivisionError points to in your code is *not* the
raised exception.
Notice that I get my customized exception type when I explicitly raise
ZeroDivisionError but not when that is implicitly raised by 1/0. It
seems like I have to replace that exception type at some lower level,
but I'm not sure how/where. Does anyone know of a way to do this?
The obvious question is: What are you trying to do?
Remember that you can always catch an exception in an `except` clause and
perform whatever action you want, eg. raise *another* exception.
If you just want to change error representations (I doubt that you really
need it, tho), you might be interested in overwriting `sys.excepthook
<http://docs.python.org/lib/module-sys.html#l2h-5125>`_.
HTH,