[Python-ideas] Briefer string format

MRAB python at mrabarnett.plus.com
Sun Aug 2 17:57:27 CEST 2015


On 2015-08-02 16:37, Eric V. Smith wrote:
> On 8/1/2015 1:43 PM, Eric V. Smith wrote:
>> On 7/25/2015 3:55 PM, Eric V. Smith wrote:
>>> In trying to understand the issues for a PEP, I'm working on a sample
>>> implementation. There, I've just disallowed concatentation entirely.
>>> Compared to all of the other issues, it's really insignificant. I'll put
>>> it back at some point.
>>
>> I'm basically done with my implementation of f-strings.
>
> Here's another issue. I can't imagine this will happen often, but it
> should be addressed. It has to do with literal expressions that begin
> with a left brace.
>
> For example, this expression:
>>>> {x: y for x, y in [(1, 2), (3, 4)]}
> {1: 2, 3: 4}
>
> If you want to put it in an f-string, you'd naively write:
>
>>>> f'expr={{x: y for x, y in [(1, 2), (3, 4)]}}'
> 'expr={x: y for x, y in [(1, 2), (3, 4)]}'
>
> But as you see, this won't work because the doubled '{' and '}' chars
> are just interpreted as escaped braces, and the result is an
> uninterpreted string literal, with the doubled braces replaced by
> undoubled ones.
>
> There's currently no way around this. You could try putting a space
> between the left braces, but that fails with IndentationError:
>
>>>> f'expr={ {x: y for x, y in [(1, 2), (3, 4)]}}'
>    File "<fstring>", line 1
>      {x: y for x, y in [(1, 2), (3, 4)]}
>      ^
> IndentationError: unexpected indent
>
Why is there an IndentationError? It's an expression, not a statement,
so leading spaces should be ignored.

They're not at the Python prompt, but, then, that accepts both
statements and expressions.

> In the PEP I'm going to specify that leading spaces are skipped in an
> expression. So that last example will now work:
>
>>>> f'expr={ {x: y for x, y in [(1, 2), (3, 4)]}}'
> 'expr={1: 2, 3: 4}'
>
> Note that the right braces in that last example aren't interpreted as a
> doubled '}'. That's because the first one is part of the expression, and
> the second one ends the expression. The only time doubling braces
> matters is inside the string literal portion of an f-string.
>
> I'll reflect this "skip leading white space" decision in the PEP.
>



More information about the Python-ideas mailing list