[Python-Dev] PEP 498 (interpolated f-string) tweak

Eric V. Smith eric at trueblade.com
Sun Sep 20 21:22:55 CEST 2015


> On Sep 20, 2015, at 11:15 AM, Serhiy Storchaka <storchaka at gmail.com> wrote:
> 
>> On 20.09.15 16:51, Eric V. Smith wrote:
>>> On 9/20/2015 8:37 AM, Nick Coghlan wrote:
>>>> On 19 September 2015 at 21:03, Eric V. Smith <eric at trueblade.com> wrote:
>>>> Instead of calling __format__, I've changed the code generator to call
>>>> format(expr1, spec1). As an optimization, I might add special opcodes to
>>>> deal with this and string concatenation, but that's for another day (if
>>>> ever).
>>> 
>>> Does this mean overriding format at the module level or in builtins
>>> will affect the way f-strings are evaluated at runtime? (I don't have
>>> a strong preference one way or the other, but I think the PEP should
>>> be explicit as to the expected behaviour rather than leaving it as
>>> implementation defined).
>> 
>> Yes, in the current implementation, if you mess with format(), str(),
>> repr(), or ascii() you can break f-strings. The latter 3 are used to
>> implement !s, !r, and !a.
>> 
>> I have a plan to change this, by adding one or more opcodes to implement
>> the formatting and string joining. I'll defer a decision on updating the
>> PEP until I can establish the feasibility (and desirability) of that
>> approach.
> 
> I propose to add internal builting formatter type. Instances should be marshallable and callable. The code generated for f-strings should just load formatter constant and call it with arguments. The formatter builds resulting string by concatenating literal strings and results of formatting arguments with specified specifications.
> 
> Later we could change compiler (just peephole optimizer?) to replace literal_string.format(*args) and literal_string % args with calling precompiled formatter.
> 
> Later we could rewrite str.format, str.__mod__ and re.sub to create temporary formatter object and call it.
> 
> Later we could expose public API for creating formatter object. It can be used by third-party template engines.
> 

I think this is InterpolationTemplate from PEP 501.

Eric. 



More information about the Python-Dev mailing list