[Python-ideas] f-string "debug" conversion

Steven D'Aprano steve at pearwood.info
Wed Oct 3 03:54:10 EDT 2018

On Tue, Oct 02, 2018 at 08:27:03PM -0400, Eric V. Smith wrote:

> Here’s the idea: for f-strings, we add a !d conversion operator, which 
> is superficially similar to !s, !r, and !a. The meaning of !d is: 
> produce the text of the expression (not its value!),

I SO WANT THIS AS A GENERAL FEATURE, not just for f-strings, it hurts.

Actually what I want is an executable object (a function?) which has the 
AST and text of the expression attached. If putting this into f-strings 
is a first step towards getting this thunk-like thing, then I don't 
need to read any further, I'm +10000 :-)

But considering the proposal as you give it:

> followed by an 
> equal sign, followed by the repr of the value of the expression. So:
> value = 10
> s = 'a string!'
> print(f'{value!d}')
> print(f'next: {value+1!d}')
> print(f'{s!d}')
> produces:
> value=10
> next: value+1=11
> s='a string!'

I can see lots of arguments about whether the equals sign should have 
spaces around it. 

Maybe !d for no spaces and !D for spaces?

print(f'next: {value+1!d}')
print(f'next: {value+1!D}')

would print

next: value+1=11
next: value+1 = 11

> I’m not proposing this for str.format(). It would only really make sense 
> for named arguments, and I don’t think 
> print('{value!d}'.format(value=value) is much of a win.

I'm not so sure that it only makes sense for named arguments. I think it 
works for arbitrary expressions too:

f'{len("NOBODY expects the Spanish Inquisition!")!d}'

ought to return

'len("NOBODY expects the Spanish Inquisition!")=39'

which I can see being very useful in debugging expressions.

This is perhaps the first time I've been excited and enthusiastic about 
f-strings. A definite +1 on this.


More information about the Python-ideas mailing list