In numpy, when you make a mistake, the error doesn't tell you about all the numpy internals, just the user-level error made. For example:
import numpy as np
A = np.ones([1,2])
B = np.ones([2,3])
A+B
spits back
Traceback (most recent call last):
File "/home/roderic/Desktop/scratchpad.py", line 5, in <module>
A+B
ValueError: operands could not be broadcast together with shapes (1,2) (2,3)
Notice how it doesn't tell you about all the internal bouncing around that numpy did in order to determine that you are multiplying incompatible matrices, nor where the ValueError was raised exactly. I want to do the same for my project, where the traceback should stop outside of the module internals (unless I am on debug mode). So, if the traceback is 10 steps long, and the first 4 are on user level, and the last 6 are internal processing from my library, I only want to feature the first 4.
I know how to extract the stack, but I don't know how to modify it and re-inject it before raising the exception. I also assume this is considered a bad idea, and if so, I'd like to know what my other options are.
My horrible temporary solution is looking like this:
except AssertionError as error:
# something went wrong, the input was not correct
print( "Traceback (most recent call last):")
for filepath, line_no, namespace, line in traceback.extract_stack():
if os.path.basename(filepath)=='MyModuleName.py': break
print( ' File "{filepath}", line {line_no}, in {namespace}\n'
' {line}'.format(**locals()))
exit()
limit
parameter to strip out unneeded information about the traceback. And if that's not an option than you can print a partial version of the stacktrace usingprint(traceback.format_list(your_filter_func(traceback.extract_stack())))
to make printing easier.