3 ms·
> What’s the easiest possible way to cause stacktraces to also dump local variable information? I feel like this is a feature that should be built into the lang
by Sohcahtoa82 2y ago
> What’s the easiest possible way to cause stacktraces to also dump local variable information? I feel like this is a feature that should be built into the language…
That is built into Python!
import sys
def div(x, y):
return x / y
try:
print(div(1, 0))
except ZeroDivisionError as e:
print("Div by zero!")
print("Locals:")
_, _, tb = sys.exc_info()
print(tb.tb_next.tb_frame.f_locals)
This will output:
Div by zero!
Locals:
{'x': 1, 'y': 0}
https://stackoverflow.com/a/5328139 https://stackoverflow.com/a/5328139 has a more thorough implementation that will print you entire stack of local variables.