[Python-Dev] Subtle difference between f-strings and str.format()

Stefan Behnel stefan_ml at behnel.de
Sat Mar 31 04:17:37 EDT 2018


Serhiy Storchaka schrieb am 28.03.2018 um 17:27:
> There is a subtle semantic difference between str.format() and "equivalent"
> f-string.
> 
>     '{}{}'.format(a, b)
>     f'{a}{b}'
> 
> In the former case b is evaluated before formatting a. This is equivalent to
> 
>     t1 = a
>     t2 = b
>     t3 = format(t1)
>     t4 = format(t2)
>     r = t3 + t4
> 
> In the latter case a is formatted before evaluating b. This is equivalent to
> 
>     t1 = a
>     t2 = format(t1)
>     t3 = b
>     t4 = format(t3)
>     r = t2 + t4
> 
> In most cases this doesn't matter, but when implement the optimization that
> transforms the former expression to the the latter one ([1], [2]) we have
> to make a decision what to do with this difference.
> 
> [1] https://bugs.python.org/issue28307
> [2] https://bugs.python.org/issue28308

Just for the record, I implemented the translation-time transformation
described in [1] (i.e. '%' string formatting with a tuple) in Cython 0.28
(released mid of March, see [3]), and it has the same problem of changing
the behaviour. I was aware of this at the time I implemented it, but
decided to postpone the fix of evaluating the arguments before formatting
them, as I considered it low priority compared to the faster execution. I
expect failures during formatting to be rare in real-world code, where
string building tends to be at the end of a processing step that should
catch many value problems already. Rare, but not impossible.

I do consider this change in behaviour a bug that should be fixed, and I
would also consider it a bug in CPython if it was added there.

Stefan


[3]
https://github.com/cython/cython/blob/de618c0141ae818e7a4c35d46256d98e6b6dba53/Cython/Compiler/Optimize.py#L4261



More information about the Python-Dev mailing list