I'm trying to override the printed output from an Exception subclass in Python after the exception has been raised and I'm having no luck getting my override to actually be called.
def str_override(self):
"""
Override the output with a fixed string
"""
return "Override!"
def reraise(exception):
"""
Re-raise an exception and override its output
"""
exception.__str__ = types.MethodType(str_override, exception, type(exception))
# Re-raise and remove ourselves from the stack trace.
raise exception, None, sys.exc_info()[-1]
def test():
"""
Should output "Override!" Actually outputs "Bah Humbug"
"""
try:
try:
raise Exception("Bah Humbug")
except Exception, e:
reraise(e, "Said Scrooge")
except Exception, e:
print e
Any idea why this doesn't actually override the str method? Introspecting the instance variables shows that the method is actually overridden with the method but it's like Python just refuses to call it through print.
What am I missing here?