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

Stefan Behnel stefan_ml at behnel.de
Wed Mar 28 15:19:35 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.

I agree that it's not normally a problem, but if the formatting of 'a'
fails and raises an exception, then 'b' will not get evaluated at all in
the second case. Whether this difference is subtle or not is seems to
depend largely on the code at hand.

Stefan



More information about the Python-Dev mailing list