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

Eric V. Smith eric at trueblade.com
Wed Oct 3 19:38:52 EDT 2018

On 10/3/2018 7:07 AM, Eric V. Smith wrote:
> On 10/3/2018 12:23 AM, Tim Peters wrote:
>> [Eric V. Smith <eric at trueblade.com <mailto:eric at trueblade.com>>]
>>     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!), followed by an
>>     equal sign, followed by the repr of the value of the expression.
>> ...
>>     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.
>> Me neither ;-)  But what if
>>      {EXPR!d:FMT}
>> acted like the current
>>      EXPR={EXPR:FMT}
>> ?  I'd find _that_ useful often.  For example, when displaying floats, 
>> where the repe is almost never what I want to see.
>>  >>> f"math.pi={math.pi:.2f}"
>> 'math.pi=3.14'
>> I have plenty of code already embedding stuff of the form
>>      EXPR {EXPR:FMT}
>> and don't really care whether there's a space or an "=" between the 
>> chunks.  "!d" could act like a macro-expansion operator automating a 
>> mechanical transformation inside the f-string.  Then I could read "!d" 
>> as "duplicate" instead of as "debug" ;-)
> That's a very interesting idea. It breaks the expectation (which might 
> be mine alone!) that the format spec is used on the result of the 
> conversion specifier (!s, !r). But maybe that's okay. It does seem 
> generally more useful than the format spec being used on the repr of the 
> evaluated expression.

After giving this some more thought, the problem with this approach is 
that there's no way to get the repr of the object, which for debugging 
can be pretty useful (think strings). Remember, by default 
object.__format__ calls object.__str__.

I guess we could get around this by combining !d and !r and assigning 
some meaning to that, which I'd rather not do.

Or, this occurred to me right before hitting "send": if there's no 
format spec, use repr(expr). If there is one (even if it's zero-length), 
use format(expr, spec). I'll have to think on that for a while. Maybe 
there's too much voodoo going on there.


More information about the Python-ideas mailing list