If you want just the single line printed, without the whole traceback, here's one way to handle it:
import sys
i = 0
try:
assert i == 1, f"expected 1, got {i}"
except AssertionError as e:
print(e)
# print(e, file=sys.stderr) # to print to stderr
sys.exit(1) # exit program with error
You could also intercept the system excepthook or something similar and alter how the traceback is printed out.
Here is working with an excepthook:
import sys
def assertion_excepthook(type, value, traceback):
if type is AssertionError:
print(value)
# with line number:
print(f"{traceback.tb_lineno}: {value}")
else:
sys.__excepthook__(type, value, traceback)
sys.excepthook = assertion_excepthook
i = 0
assert i == 1, f"expected 1, got {i}"
This solution is a little more overhead but it means you won't have to do several try/except blocks.
AssertionError: expected 1, got 0is displayed after the traceback. You can hide the traceback (as in the answer below), but I don't see what's that useful for.