1

If I do the following in python

i = 0
assert i == 1, f"expected 1, got {i}"

The assert message is

Traceback (most recent call last): ... assert i == 1, f"expected 1, got {i}"

How do I get it to show expected 1, got 0? It doesn't seem to expand the dynamic string first but treat it as a literal.

3
  • 2
    Can you paste the entire traceback? I think that's just showing us the line of code that raised the exception, not the actual error message. Commented Jan 9, 2021 at 8:39
  • 1
    It works fine on my end. Can you show us your full traceback? Commented Jan 9, 2021 at 8:43
  • The problem is probably at your console scroll, output buffer, failure to notice the error message, or something. The AssertionError: expected 1, got 0 is displayed after the traceback. You can hide the traceback (as in the answer below), but I don't see what's that useful for. Commented Jan 9, 2021 at 12:04

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Probably best to print to stderr
@costaparas good point, I'll add that in!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.