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

Mikhail V mikhailwas at gmail.com
Thu Oct 4 11:31:24 EDT 2018


On Wed, Oct 3, 2018 at 3:28 AM Eric V. Smith <eric at trueblade.com> 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!), followed by an
> equal sign, followed by the repr of the value of the expression. So:
> [...]
> 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!r}')
>
> and would now be:
>
> print(f'{value!d}')
>
> There have been discussions about ways to specify str() vs. repr(),
> using characters other than '=', adding spaces, etc. But they all end up
> over-complicating what should be a simple tool, not a Swiss Army knife.
>
> Thoughts?
>
> Eric

I think the feature is useful to avoid re-typing the expressions.
But still, the syntax is a bit obscure, and the feature
is very limited (can't construct anything but "x=x").
That makes me personally less enthusiastic about using it instead
of the common: f" x = {x}". (yes I use spaces around = most of
the time and probably only spaces for table-like output)

Did you think about more general syntax for repetitions?
If there would be a way to repeat entries, one could do similar output
without much extra typing.

E.g. an asterisk for "same expression" ?

    price = 10
    s = f"{price} {*}"        # 10 10

And then using say {expr !} would print _only_ the expression string.
So with e.g. some variable:

    variable = 13.18654937
    f"{variable !} = {*:.4f}  {*:.2f}  {*:.0f}"
prints:
    variable = 13.1865  13.19  13

Something like that. It is more complex implementation, etc,
but has better, verbose appearance Imo and not so limited.
And custom formatting is important to achieve a readable output.


Mikhail


More information about the Python-ideas mailing list