<br><br><div class="gmail_quote">On Sat, May 28, 2011 at 12:43 PM, Eric Smith <span dir="ltr"><<a href="mailto:eric@trueblade.com">eric@trueblade.com</a>></span> wrote:<blockquote class="gmail_quote" style="margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 0.8ex; border-left-width: 1px; border-left-color: rgb(204, 204, 204); border-left-style: solid; padding-left: 1ex; position: static; z-index: auto; ">
And Python 3.x has the exact same implementation, although it's only<br>
included for unicode strings. It would not be difficult to add .format()<br>
for bytes.<br>
<br>
There have been various discussions over the years of how to actually do<br>
that. I think the most recent one was to add an __bformat__ method.</blockquote></div><br>Well, that's actually great idea I think. format method on bytes could produce some data which is not an ascii, and eventually became struct.pack on steroids. The struct.pack has plenty of problems:<div>
<br></div><div>* unable to use named fields, which is usefull to describe big structures</div><div>* all fields are fixed-length, which is unfortunate for today's trend of variable length integers</div><div>* can't specify separators between fields</div>
<div><br></div><div>I also use str(intvalue).encode('ascii') idiom a lot. So probably I'd suggest to have something like</div><div>__bformat__ with format values somewhat similar to ones struct.pack has along with str-like ones for integers. Also it might be useful to have `!len` conversion for bytes fields, for easier encoding of length-prefixed strings.</div>
<div><br></div><div>To show an example, here is how two-chunk png file can be encoded:</div><div><br></div><div>(b"\x89PNG\r\n\x1A\n"</div><div> b"{s1!len:>L}IHDR{s1}{crc1:>L}"</div><div> b"{s2!len:>L}IDAT{s2}{crc2:>L}\0\0\0\0IEND".format(</div>
<div> s1=section1, crc1=crc(section1),</div><div> s2=section2, crc2=crc(section2)))</div><div><br>-- <br><div>Paul</div><br>
</div>