Pprint for f-string?

We have f"{variable = =}" to print the value of a variable, which is fine, but how about adding some modifier so that the output, specially of dicts, is formatted as if put through pprint?

I would like to domething like:

In [1]: # import pprint  - whoops, would like to not need this.

In [2]: calories = dict(milk='OK', toffee='high', beer='acceptable', spinach='so?')

In [3]: print(f"{calories = }")
calories = {'milk': 'OK', 'toffee': 'high', 'beer': 'acceptable', 'spinach': 'so?'}

In [4]: print(f"{calories = :pp(width=30)}")
calories = {'milk': 'OK',
 'toffee': 'high',
 'beer': 'acceptable',
 'spinach': 'so?'}
>>> from pprint import pformat as pf
>>> print(f"calories = {pf(calories, width=30)}")
calories = {'beer': 'acceptable',
 'milk': 'OK',
 'spinach': 'so?',
 'toffee': 'high'}
4 Likes

Yep, but repeating calories.
I’d just like to write something shorter and have it “Do the right thing”.

Without repeating calories:

>>> print(f"{pf(calories, width=30) = !s}")
pf(calories, width=30) = {'beer': 'acceptable',
 'milk': 'OK',
 'spinach': 'so?',
 'toffee': 'high'}

If you do not like extra pf(...) in the output – sorry, this feature is for debugging only.

5 Likes