jimbaker / tagstr

This repo contains an issue tracker, examples, and early work related to PEP 999: Tag Strings
51 stars 6 forks source link

Would tagged strings supported nested expressions in the format specifier? #4

Closed ericvsmith closed 1 year ago

ericvsmith commented 2 years ago

I'm creating this issue just so we won't forget the conversation from this morning.

f-strings support expressions in the format specifier:

>>> width=10
>>> value=42
>>> f'{value:^{width}}'
'    42    '

Further nesting is not supported:

>>> f'result: {value:{width:{0}}.{precision:1}}'
  File "<stdin>", line 1
    f'result: {value:{width:{0}}.{precision:1}}'
                                                ^
SyntaxError: f-string: expressions nested too deeply
gvanrossum commented 2 years ago

I propose that width is evaluated and the result interpolated in the format spec before it is passed into the Thunk.

ericvsmith commented 2 years ago

I think early evaluation of the format spec is reasonable. But then how do you get the entire raw string back?

jimbaker commented 2 years ago

One nice alternative to eager evaluation is to represent formatspec as Sequence[str | Thunk]. While this means that Thunk is recursive, we would still only allow one level of nesting in the parser itself.

We also can get back the entire raw string, since this is true of our Thunk support.

Lastly, this would mean the args to the tag would be deeply immutable, which seems like a nice property.

gvanrossum commented 1 year ago

This has been solved by PEP 701 in favor of allowing nesting.

It uses eager evaluation for the spec, so the tag function would receive whatever f"{width:{0}}.{precision:1}" produces. I'm personally okay with that (but it should be called out in the PEP and docs).

jimbaker commented 1 year ago

Sounds good about following what was done in PEP 701, closing this issue out accordingly.