Skip to main content

Python’s f-strings support = for self-documenting expressions

  • Tagged with python
  • Posted

The f-string f"{x=}" expands to f"x={x}".

I was reading PEP 736, a rejected proposal for a shorthand syntax for keyword arguments, and it mentioned a new-to-me bit of prior art:

Python already possesses a very similar feature in f-string interpolation where f'{x=}' is effectively expanded to f'x={x}' (see related GitHub issue).

It supports both single variables and more complex expressions. Here’s a few examples:

>>> x = 42
>>> f"{x=}"
'x=42'
>>> f"{1+2=}"
'1+2=3'
>>> f"{(1+2)*3=}"
'(1+2)*3=9'

This is described in What’s New In Python 3.8; this feature was realised nearly six years ago but I’ve never come across it before.