replacing built-in exception types
Calvin Spealman
ironfroggy at socialserve.com
Tue Dec 11 21:39:47 EST 2007
Similarly I would ask then, why would you want to set class
attributes on the built-in Exception classes?
On Dec 11, 2007, at 9:29 PM, Nishkar Grover wrote:
>
> I'm trying to replace the built-in base exception class with a
> subclass of itself in python 2.5 because we can no longer add
> attributes to that...
>
> % python2.4 -c 'import exceptions; exceptions.Exception.bar = 1234'
>
> % python2.5 -c 'import exceptions; exceptions.Exception.bar = 1234'
> Traceback (most recent call last):
> File "<string>", line 1, in <module>
> TypeError: can't set attributes of built-in/extension type
> 'exceptions.Exception'
>
> % python2.5 -c 'import exceptions; exceptions.BaseException.bar =
> 1234'
> Traceback (most recent call last):
> File "<string>", line 1, in <module>
> TypeError: can't set attributes of built-in/extension type
> 'exceptions.BaseException'
>
> I already have a way to programatically construct the hierarchy of
> subclasses, so for example, my subclass of OSError is a subclass of
> the built-in OSError and a subclass of my subclass of
> EnvironmentError. The only thing left to do is find a way to
> replace the built-in exception types with my custom ones.
>
> - Nishkar
>
>
> Calvin Spealman wrote:
>> Why would you do this? How to do it, if its even possible, is far
>> less
>> important than if you should even attempt it in the first place.
>> On Dec 11, 2007, at 3:51 PM, 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
>>> >>>
>>> >>> 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
>>> >>>
>>>
>>> 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?
>>>
>>> - Nishkar
>>>
>>> --http://mail.python.org/mailman/listinfo/python-list
More information about the Python-list
mailing list