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

Serhiy Storchaka storchaka at gmail.com
Wed Mar 28 14:54:51 EDT 2018


28.03.18 21:30, Tim Peters пише:

> [Tim]
>> I have a hard time imaging how that could have come to be, but if it's
>> true I'd say the unoptimized code was plain wrong.  The dumbest
>> possible way to implement `f() and g()` is also the correct ;-) way:
>>
>> result = f()
>> if not bool(result):
>>      result = g()
> Heh - that's entirely wrong, isn't it?  That's how `or` is implemented ;-)
>
> Same top-level point, though:
>
> result = f()
> if bool(result):
>      result = g()

Optimized

     if f() and g():
         spam()

is equivalent to

     result = f()
     if bool(result):
         result = g()
         if bool(result):
             spam()

Without optimization it would be equivalent to

     result = f()
     if bool(result):
         result = g()
     if bool(result):
         spam()

It calls bool() for the result of f() twice if it is false.

Thus there is a small difference between

     if f() and g():
         spam()

and

     tmp = f() and g()
     if tmp:
         spam()



More information about the Python-Dev mailing list