How to allow arbitrary expressions in format strings

As the original RFC author for the incoming variable name shorthand, I'd personally be ok to never see arbitrary expressions allowed in format! and friends.

I'm a very frequent Python user, and make heavy use of f-string formatting. It's only very rarely where I see something other than a simple binding that doesn't look like an eyesore.

Consider something like this:

items = { "x": 1, "y": 2 }
print(f"Trace: {items['x']=}, {items['y']=}")

The interpolated expressions are "just" lookups (plus magic trailing = to print out the expression). There's quite a heavy dose of symbols and strings-within-strings; there could even be hidden side effects in an exotic __getitem__ implementation.

With the limited interpolation we gain from RFC 2795, the result the programmer is forced to write is (I think) much easier to read and review:

items = { "x": 1, "y": 2 }
x = items['x']
y = items['y']
print(f"Trace: items['x']={x}, items['y']={y}")

The only expression I personally would be interested in as follow up from RFC 2795 is support for dotted.names, which I believe are a simple backwards-compatible extension to the current macros.

However, not even dotted.names are side-effect free (in the case misbehaving Deref implementations). Also, I think everyone has their own subset of expressions which they would want to have supported. As supporting any subset smaller than all general expressions is a subjective topic, and I definitely don't want to see general expressions, I'd be quite happy to settle for not allowing any expressions at all. It's not that bad to write format!("Name = {name}", name = self.name).

8 Likes