[Python-ideas] Briefer string format
Eric V. Smith
eric at trueblade.com
Mon Jul 20 19:57:33 CEST 2015
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.
>
> Historically, the `x` notation as an alias for repr(x) was meant to play
> this role -- you'd write '...' + `var` + '...', but it wasn't brief
> enough, and the `` are hard to see. f'...' is more explicit, and can be
> combined with r'...' and b'...' (or both) as needed.
We didn't implement b''.format(), for a variety of reasons. Mostly to do
with user-defined types returning unicode from __format__, if I recall
correctly.
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?
I think I could leverage _string.formatter_parser() to do this, although
it's been a while since I wrote that. And I'm not sure what's available
at compile time. But I can look into it.
I guess the other option is to have it generate:
'x:{a.x} y:{y}'.format_map(collections.ChainMap(globals(), locals(),
__builtins__))
That way, I wouldn't have to parse the string to pick out what variables
are referenced in it, then have .format() parse it again.
Eric.
More information about the Python-ideas
mailing list