[Python-ideas] Briefer string format

Steve Dower Steve.Dower at microsoft.com
Mon Jul 20 22:17:25 CEST 2015


Guido van Rossum wrote:
> (Our posts crossed, to some extent.)

Yeah, mine delayed about 20 minutes after I sent it before I saw the list send it out. Not sure what's going on there...

> On Mon, Jul 20, 2015 at 8:41 PM, Steve Dower <Steve.Dower at microsoft.com> wrote:
> Eric V. Smith wrote:
>> On 07/20/2015 01:25 PM, Guido van Rossum wrote:
>>> Perhaps surprisingly, I find myself leaning in favor of the
>>> f'...{var}...' form. It is explicit in the variable name.
>> 
>> [...]
>> 
>>> So the idea is that
>>> f'x:{a.x} y:{y}'
>>> would translate to bytecode that does:
>>> 'x:{a.x} y:{y}'.format(a=a, y=y)
>>>
>>> Correct?
>> 
>> That's exactly what I had in mind, at least. Indexing is supported in format
>> strings too, so f'{a[1]}' also becomes '{a[1]}'.format(a=a), but I don't think
>> there are any other strange cases here. I would vote for f'{}' or f'{0}' to just
>> be a SyntaxError.
>
> +1 on that last sentence. But I prefer a slightly different way of implementing
> (see my reply to Eric).

Yep, saw that and after giving it some thought I agree. Initially I liked the cleanliness of not modifying the original string, but the transform does seem easier to explain as "lifting" each expression out of the string (at least compared to "lifting the first part of each expression and combining duplicates and assuming they are always the same value").

One catch here is that '{a[b]}' has to transform to '{}'.format(a['b']) and not .format(a[b]), which is fine but an extra step. IIRC you can only use ints and strs as keys in a format string.

>> I briefly looked into how this would be implemented and while it's not quite
>> trivial/localized, it should be relatively straightforward if we don't allow
>> implicit merging of f'' strings. If we wanted to allow implicit merging then
>> we'd need to touch more code, but I don't see any benefit from allowing it at
>> all, let alone enough to justify seriously messing with this part of the parser.
> 
> Not sure what you mean by "implicit merging" -- if you mean literal
> concatenation (e.g. 'foo' "bar" == 'foobar') then I think it should be allowed,
> just like we support mixing quotes and r''.

Except we don't really have a literal now - it's an expression.

Does f"{a}" "{b}" become "{}{}".format(a, b), "{}".format(a) + "{b}" or "{}{{b}}".format(a)? What about f"{" f"{a}" f"}"? Should something that looks like literal concatenation silently become runtime concatenation?

Yes, it's possible to answer and define all of these, but I don't see how it adds value (though I am one of those people who never use literal concatenation and advise others not to use it either), and I see plenty of ways it would unnecessarily extend discussion and prevent actually getting something done.

Cheers,
Steve

> --
> --Guido van Rossum (python.org/~guido)



More information about the Python-ideas mailing list