Python: Can I overload the raise statement with def __raise__(self):?

python, raise

Solution

As the other answer says, there is no `__raise__` special method. There was a thread in 2004 on comp.lang.python where someone suggested adding such a method, but I don't think there was any followup to that. The only way I can think of to hook exception raising is either by patching the interpreter, or some kind of source or bytecode rewriting that inserts a function call next to the raise operation.

Problem

Here's my exception class that is using raise: ``` class SCE(Exception): """ An error while performing SCE functions. """ def __init__(self, value=None): """ Message: A string message or an iterable of strings. """ if value is None: self._values = [] elif isinstance(value, str): self._values = [value] else: self._values = list(value) def __raise__(self): print('raising') if not len(self._values): return def __str__(self): return self.__repr__() def __iter__(self): return iter(self._values) def __repr__(self): return repr(self._values) ``` Currently if I raise this exception with no value I get traceback followed by: ``` __main__.SCE: [] ``` Instead of what I expected which was: ``` raising >>> ``` How do you overload `raise`?

Original source

Related problems