osdir.com


[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

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


On Wed, Mar 28, 2018 at 06:27:19PM +0300, Serhiy Storchaka wrote:

> 2. Change the semantic of f-strings. Make it closer to the semantic of 
> str.format(): evaluate all subexpressions first than format them. This 
> can be implemented in two ways:
> 
> 2a) Add additional instructions for stack manipulations. This will slow 
> down f-strings.
> 
> 2b) Introduce a new complex opcode that will replace FORMAT_VALUE and 
> BUILD_STRING. This will speed up f-strings.

If the aim here is to be an optimization, then I vote strongly for 2b.

That gives you *faster f-strings* that have the same order-of-evaluation 
of normal method calls, so that when you optimize str.format into an 
f-string, not only is the behaviour identical, but they will be even 
faster than with option 3.

Python's execution model implies that 

    obj.method(expression_a, expression_b)

should fully evaluate both expressions before they are passed to the 
method. Making str.format a magical special case that violates that rule 
should be a last resort.

In this case, we can have our cake and eat it too: both the str.format 
to f-string optimization and keeping the normal evaluation rules. And as 
a bonus, we make f-strings even faster.

I say "we", but of course it is Serhiy doing the work, thank you.

Is there a down-side to 2b? It sounds like something you might end up 
doing at a later date regardless of what you do now.


-- 
Steve