python - Raise an exception with traceback starting from caller -
i'm trying make automated test framework side-project , use creating assertion checks.
running in python...
assert(false)
gives this...
traceback (most recent call last): file "test.py", line 1, in <module> assert(false) assertionerror
as can see traceback lowest level assert(false)
. made custom assert prints when assert succeeds.
def custom_assert(condition): if condition: print("yay! werks!") else: raise exception("nay, don't werks...") custom_assert(false)
but instead of assert
gives, custom_assert
gives me this.
traceback (most recent call last): file "test.py", line 14, in <module> custom_assert(false) file "test.py", line 12, in custom_assert raise exception("nay, don't werks...") exception: nay, don't werks...
which of course default behavior. useful 99.9999% of time, 1 time improved. it's not useful know method called raise error when condition false raised error.
how can make custom_assert
raise exception traceback starting caller, same way assert
does?
p.s.: don't want print it, want exception have modified traceback works debuggers , other tools too!
edit
to clarify, traceback want this.
traceback (most recent call last): file "test.py", line 14, in <module> custom_assert(false) exception: nay, don't werks...
essentially want similar this:
tb = none try: raise exception('foo') except exception: tb = sys.exc_info()[2] tb.tb_frame = tb.tb_frame.f_back # line doesn't work raise exception('nay doesnt werks').with_traceback(tb)
but can't assign tb_frame, , mucking around in cpython code, c-generated data structures (not python) (see sys._getframe()
) option left mock entire machinery , convince python use stack. looks jinja2 doing. if that's choose do, luck! (it's out of scope @ point)
Comments
Post a Comment