0

In the following python code, what causes the difference in outputs?

try:
    open('nonexistent')
except Exception as err:
    print(f'{err=}')
    print(f'{err}')

result:

err=FileNotFoundError(2, 'No such file or directory')
[Errno 2] No such file or directory: 'nonexistent'

In this instance, the second is more useful, but I'm surprised there's a difference at all. What's the cause of this, and what's the logic behind this design decision?

I'm using Python 3.8.3.

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
extremeaxe5
  • 723
  • 3
  • 13
  • 1
    Your code is very different from your title. Your title says `f"a={a}"`. Your code just says `f'{err}'`, not `f'err={err}'`. – user2357112 Apr 09 '23 at 02:14
  • Does this answer your question? [What does = (equal) do in f-strings inside the expression curly brackets?](https://stackoverflow.com/questions/59661904/what-does-equal-do-in-f-strings-inside-the-expression-curly-brackets) – jamesdlin Apr 09 '23 at 02:23

1 Answers1

3

Quoting the f-string documentation:

When the equal sign '=' is provided, the output will have the expression text, the '=' and the evaluated value. Spaces after the opening brace '{', within the expression and after the '=' are all retained in the output. By default, the '=' causes the repr() of the expression to be provided, unless there is a format specified. When a format is specified it defaults to the str() of the expression unless a conversion '!r' is declared.

Since you did not specify a format, f'{err=}' applies repr instead of str to err. This is a more useful default than str for the debugging use cases the = f-string syntax was designed for.

user2357112
  • 260,549
  • 28
  • 431
  • 505
  • It's probably worth noting that `f{err}` gives `str(err)` (explained [here](https://docs.python.org/3/library/functions.html#format)) and hence the difference noted by OP – Nick Apr 09 '23 at 02:33