A more detailed stack trace that includes all local variables at each level can be achieved by utilizing the stack-snapshot library.
Firstly, use pip install stack-snapshot
command to install this library, then just put one line in your code:
import stack_snapshot; stack_snapshot.init()
An example:
import stack_snapshot
def inner(x, y):
return x / y
stack_snapshot.init()
x = 1; y = 0
print(inner(x, y))
When stack snapshotting is not enabled:
Traceback (most recent call last):
File "PyStackSnapshot\test.py", line 9, in <module>
print(inner(x,y))
File "PyStackSnapshot\test.py", line 4, in inner
if y == 0: raise ZeroDivisionError
ZeroDivisionError
After enabling stack snapshotting, it is easier and more convenient to to pinpoint the issue while knowing the values of x
and y
:
-------------------- Error: --------------------
Traceback (most recent call last):
File "PyStackSnapshot\test.py", line 9, in <module>
print(inner(x,y))
File "PyStackSnapshot\test.py", line 4, in inner
if y == 0: raise ZeroDivisionError
ZeroDivisionError
Local variables of inner (test.py):
x = 1
y = 0
Global variables of <module>:
__file__ = 'PyStackSnapshot\\test.py'
__name__ = '__main__'
...
inner = <function inner at 0x03221810>
x = 1
y = 0
-----------------------------------------------
Exceptions can also be manually output:
import stack_snapshot
def inner(x, y):
return x / y
stack_snapshot.init()
try:
print(inner(1, 0))
except Exception as err:
if hasattr(err, "stack_snapshot"):
print("Stack depth: ", len(err.stack_snapshot)) # When taking snapshot is enabled, all exception objects automatically have a stack_snapshot attribute added
stack_snapshot.trace_error()
It works by just modifying the __new__
method such as ValueError.__new__
,
or redirecting the function call to the exception class such as ValueError
.
Additionally, traced variable information can be pasted into generative AI tools including ChatGPT to let them generate more precise codes.
More detailed usage and how it works can be seen here: PyStackSnapshot ยท GitHub, and I'm the developer of stack-snapshot
library.