This is Larry Hasting’s idea, proposed at the core sprints earlier this month (it looks like Larry isn’t on Discourse yet, so I can’t @-mention him yet). I mentioned it to a few people there, but I haven’t had time to work on it yet. I’m posting it here mostly as a way to get experience with Discourse, but feel free to discuss it here. It really belongs on python-ideas. If we like it, I’ll eventually bring it up there.
Here’s the idea: 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!), followed by an equal sign, followed by the value of the expression. So:
value=10
print(f'{value!d}')
produces:
value=10
and:
print(f'next: {value+1!d}')
produces:
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.
The result is a string, so if you really wanted to, you could use a string formatting spec. So:
print(f'*{value!d:^20}*'
would produce:
* value=10 *
Although I don’t think that would be very useful in general.
The mnemonic is !d
for “debugging”. I’d wanted to use !=
, because there’s an equal sign involved in the result, but =
is the one character that can’t be used after !
(it’s “not equal” in expressions, and f-strings look specifically for that case). I also mentioned !!
, but I think I prefer !d
as being less confusing.
This would be used in debugging print statements, that currently end up looking like:
print(f'value={value}')
Thoughts?
My feeling is: I’m not sure it’s a great idea, but I’d use it every day if it existed.