[Python-ideas] Binary f-strings

Andrew Barnert abarnert at yahoo.com
Mon Sep 28 05:48:02 CEST 2015


On Sep 27, 2015, at 18:23, Eric V. Smith <eric at trueblade.com> wrote:
> 
> The only place this is likely to be a problem is when formatting unicode
> string values. No other built-in type is going to have a non-ascii
> compatible character in its __format__, unless you do tricky things with
> datetime format_specs. Of course user-defined types can return any
> unicode chars from __format__.

The fact that it can't handle bytes and bytes-like types makes this much less useful than %.

Beyond that, the fact that it only works reliably for the same types as %, minus bytes, plus a few others including datetime means the benefit isn't nearly as large as for f-strings and str.format, which work reliably for every type in the world, and extensibly so for many types. And meanwhile, the cost is much higher, from code that seems to work if you don't test it well to even higher performance costs (and usually in code that needs performance more).

Of course you could create a __bformat__(*args, encoding, errors, **kw) protocol (where object.__bformat__ just returns self.__format__(*args, **kw).encode(encoding, errors)), which has the same effect as your proposal except that types that need to know they're being bytes-formatted to do something reasonable, or that just want to know so they can optimize, can do so. And this of course lets you add __bformat__ to bytes, etc.--although it doesn't seem to help for types that support the buffer protocol, so it's still not as good as %b. But I don't think anyone will want that.


More information about the Python-ideas mailing list