Splice decorator out of exception stack trace?

Peter Otten __peter__ at web.de
Wed Apr 22 21:08:12 CEST 2009


Ben Weaver wrote:

> Hi,
> 
> Is there any way to "splice" a decorator out of an exception stack
> trace?  For example:
> 
>>>> def decorator(proc):
> ...     def internal(*args, **kwargs):
> ...         return proc(*args, **kwargs)
> ...     return internal
> 
>>>> @decorator
> ... def foo():
> ...     assert False, 'simulate failure'
> 
>>>> foo()
> Traceback (most recent call last):
>  ...
>  File "<...>", line 1, in <module>
>  File "<...>", line 3, in internal
>  File "<...>", line 3, in foo
> AssertionError: simulate failure
> 
> I would like to know if it's possible to somehow end up with this
> stack trace instead:
> 
>  File "<...>", line 1, in <module>
>  File "<...>", line 3, in foo

It is possible, but not a good idea. You are misleading developers hunting
for bugs.

import sys

def crash():
    1/0

def deco(f):
    def g(*args, **kw):
        try:
            print "entering f%s" % (args,)
            f(*args, **kw)
        except:
            v, t, tb = sys.exc_info()
            raise v, None, tb.tb_next
    return g

@deco
def f(n):
    if n:
        f(n-1)
    else:
        crash()


f(5)

Ouput:

$ python doctored_traceback.py
entering f(5,)
entering f(4,)
entering f(3,)
entering f(2,)
entering f(1,)
entering f(0,)
Traceback (most recent call last):
  File "doctored_traceback.py", line 24, in <module>
    f(5)
  File "doctored_traceback.py", line 19, in f
    f(n-1)
  File "doctored_traceback.py", line 19, in f
    f(n-1)
  File "doctored_traceback.py", line 19, in f
    f(n-1)
  File "doctored_traceback.py", line 19, in f
    f(n-1)
  File "doctored_traceback.py", line 19, in f
    f(n-1)
  File "doctored_traceback.py", line 21, in f
    crash()
  File "doctored_traceback.py", line 4, in crash
    1/0
ZeroDivisionError

Peter



More information about the Python-list mailing list