I'm facing (aesthetic) problems with long f-string expressions in Python. For example, this code snippet
if __name__ == '__main__':
x_true = 3
x_prov = 4
assert x_prov == x_true, f'The provided value for x, namely {x_prov}, is invalid, \
the true value should be {x_true}!'
gives the following error, which is totally expected, of course:
AssertionError: The provided value for x, namely 4, is invalid, the true value should be 3!
There is an unwanted indentation in the error message that in my opinion looks very ugly, though. One way to circumvent this is to write
if __name__ == '__main__':
x_true = 3
x_prov = 4
assert x_prov == x_true, f'The provided value for x, namely {x_prov}, is invalid, \
the true value should be {x_true}!'
# Do sth else.
However, this also looks ugly to me, as now the second line of the string has the same indentation as the outer '__main__'
function. Is there a way to have the AssertionError displayed properly without having to indent the code as the outer function?
Yes, making use of implicit string concatenation, you can do this:
if __name__ == "__main__":
x_true = 3
x_prov = 4
assert x_prov == x_true, (
f"The provided value for x, namely {x_prov}, is invalid,"
f" the true value should be {x_true}!"
)