[Python-ideas] Binary f-strings

Nick Coghlan ncoghlan at gmail.com
Sat Oct 3 16:37:04 CEST 2015


On 3 October 2015 at 02:00, Guido van Rossum <guido at python.org> wrote:
> Bingo. IMO the exact same arguments that show why f'{x} {y}' is better than
> '%s %s' % (x, y) applies to byte strings. It would be totally acceptable if
> it only took bytes (and bytearray, and memoryview) and numbers (which we can
> guarantee are rendered in ASCII only).

Given that restriction, what if we dropped the format() call in the
bytestring case, and instead always used printf-style formatting?

That is:

    bf'{packet_id}{chat_id}{sender_pk}{nonce}'

could be roughly equivalent to (with parens to help make the pieces clearer):

    (b'%b' % packet_id) + (b'%b' % chat_id) + (b'%b' % sender_pk) +
(b'%b' % nonce)

If a ":fmt" section is provided for the substitution field, it would
replace the mod-format sequence for that section:

    bf'{number:0.2d} ===> b'%0.2d' % number

With that approach, over time, printf-style formatting (aka
mod-formatting) may come to just be known as bytes formatting (even
though text strings also support it).

Something else that's neat with this: you could use the struct module
for more complex subsections of a binary protocol, while doing the
higher level composition with bf-strings*:

    bf'{header}{struct.pack('<10sHHb', record)}{footer}'

Cheers,
Nick.

* which I am now tempted to call Big Friendly Strings**, since I read
a lot of Roald Dahl books as a kid :)
** this would further mean that normal f-strings are friendly strings
in addition to being format strings ;)

-- 
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia


More information about the Python-ideas mailing list