Search code examples
pythonlistexceptionstack

How do I modify the stack list of sys.exc_info()?


I'd like to remove a couple of frames from the stack list that represent a decorator before logging it, but when I try to get to it, the debugger says that there is no such attribute as stack even though PyCharm shows it:

sys.exc_info()[2].tb_frame.stack  # <-- AttributeError, but why?

enter image description here

This is what I would like to do:

sys.exc_info()[2].tb_frame.stack = sys.exc_info()[2].tb_frame.stack[3:]


Solution

  • FWIW, I can't see an attribute for stack on a traceback.tb_frame object in python 3.8:

    try:
        raise Exception('test')
    except:
        cls, e, tb = sys.exc_info()
    
    hasattr(tb.tb_frame, 'stack')
    False
    

    You can probably do this in a for loop by tracing the tb_next attribute on the traceback:

    try:
        do_something()
    except Exception as e:
        cls, exc, tb = sys.exc_info()
    
        for _ in range(3):
            tb_next = tb.tb_next
    
            # in case you don't have that many frames
            if not tb_next:
                break
    
            tb = tb_next
    
        raise cls.with_traceback(tb)