[Python-ideas] Briefer string format

Eric V. Smith eric at trueblade.com
Tue Aug 4 22:20:10 CEST 2015


On 8/4/2015 4:05 PM, Mike Miller wrote:
> Hi,
> 
> In that message there was a logical step that I don't follow:
> 
>> For example:
>> '{a.foo}'.format(a=b[c])
>>
>> If we limit f-strings to just what str.format() string expressions can
>> represent, it would be impossible to represent this with an f-string,
>> without an intermediate assignment.
> 
>> For example:
>> f'{a[2:3]:20d}'
>>
>> We need to extract the expression "a[2:3]" and the format spec "20d". I
>> can't just scan for a colon any more, I've got to actually parse the
>> expression until I find a "}", ":", or "!" that's not part of the
>> expression so that I know where it ends.
> 
> There was a solution to this that came up early in the discussion,
> moving the identifier only:
> 
>     f'{x}{y}'           -->  '{}{}'.format(x, y)
>     f'{x:10}{y[name]}'  -->  '{:10}{[name]}'.format(x, y)
> 
> I missed the part where this was rejected.  As far as I can tell from
> your message, it is because it would be hard to parse?  But, it seems no
> harder than other solutions.  I've whipped up a simple implementation
> below.
> 

It's rejected because .format treats:
'{:10}{[name]}'.format(x, y)   -->  format(x, '10') + format(y['name'])

and we (for some definition of "we") would like:
f'{x:10}{y[name]}'             -->  format(x, '10') + format(y[name])

It's the change from y[name] to y['name'] that Guido rejected for
f-strings. And I agree: it's unfortunate that str.format works this way.
It would have been better just to say that the subscripted value must be
a literal number for str.format, but it's too late for that.

It's not hard to parse either way. All of the machinery exists to use
either the str.format approach, or the full expression approach.

> Also, Guido sounds supportive of your general process, but to my
> knowledge has not explicitly called for arbitrary expressions to be
> included.  Perhaps he could do that, or encourage us to find a more
> conservative solution?

True, he hasn't definitively stated his approval for arbitrary
expressions. I think it logically follows from our discussions. But if
he'd like to rule on it one way or the other before I'm done with the
PEP draft, that's fine with me. Or, we can just wait for the PEP.

Personally, now that I have a working implementation that I've been
using, I have to say that full expressions are pretty handy. And while I
agree you don't want to be putting hyper-complicated dict comprehensions
with lots of function calls into an f-string, the same can be said of
many places we allow expressions.

> Sorry to be a pain, but I think this part is important to get right.

No problem. It's all part of the discussion.

Eric.



More information about the Python-ideas mailing list