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

Tim Delaney timothy.c.delaney at gmail.com
Wed Mar 28 17:10:25 EDT 2018


On 29 March 2018 at 08:09, Tim Delaney <timothy.c.delaney at gmail.com> wrote:

> On 29 March 2018 at 07:39, Eric V. Smith <eric at trueblade.com> wrote:
>
>> I’d vote #3 as well.
>>
>> > On Mar 28, 2018, at 11:27 AM, Serhiy Storchaka <storchaka at gmail.com>
>> wrote:
>> >
>> > There is a subtle semantic difference between str.format() and
>> "equivalent" f-string.
>> >
>> >    '{}{}'.format(a, b)
>> >    f'{a}{b}'
>> >
>> > 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.
>>
>
Sorry about that - finger slipped and I sent an incomplete email ...

If I'm not mistaken, #3 would result in the optimiser changing str.format()
into an f-string in-place. Is this correct? We're not talking here about
people manually changing the code from str.format() to f-strings, right?

I would argue that any optimisation needs to have the same semantics as the
original code - in this case, that all arguments are evaluated before the
string is formatted.

I also assumed (not having actually used an f-string) that all its
formatting arguments were evaluated before formatting.

So my preference would be (if my understanding in the first line is
correct):

1: +0
2a: +0.5
2b: +1
3: -1

Tim Delaney
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-dev/attachments/20180329/5124c028/attachment-0001.html>


More information about the Python-Dev mailing list