[Python-ideas] Binary f-strings
Steve Dower
steve.dower at python.org
Sat Oct 3 18:20:20 CEST 2015
"Something else that's neat with this: you could use the struct module
for more complex subsections of a binary protocol"
Personally, if binary f-strings did struct packing by default, I'd want to use them all the time.
bf'{header}{record:<10sHHb}{footer}'
Practically, if they aren't equivalent to removing the b and encoding the resulting f-string, I expect we'll regularly hit confusion and misunderstanding.
$0.02
Cheers,
Steve
Top-posted from my Windows Phone
-----Original Message-----
From: "Nick Coghlan" <ncoghlan at gmail.com>
Sent: 10/3/2015 7:37
To: "Guido van Rossum" <guido at python.org>
Cc: "Python-Ideas" <python-ideas at python.org>
Subject: Re: [Python-ideas] Binary f-strings
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
_______________________________________________
Python-ideas mailing list
Python-ideas at python.org
https://mail.python.org/mailman/listinfo/python-ideas
Code of Conduct: http://python.org/psf/codeofconduct/
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20151003/d4e96c83/attachment-0001.html>
More information about the Python-ideas
mailing list