This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

Author ncoghlan
Recipients Arfrever, christian.heimes, eric.araujo, georg.brandl, gotgenes, hct, mark.dickinson, martin.panter, ncoghlan, pitrou, rhettinger, serhiy.storchaka, terry.reedy, vstinner, wiggin15
Date 2014-09-10.23:04:07
SpamBayes Score -1.0
Marked as misclassified Yes
Message-id <1410390247.33.0.30641506895.issue9951@psf.upfronthosting.co.za>
In-reply-to
Content
Just as a recap of at least some of the *current* ways to do a bytes -> hex conversion:

>>> import codecs
>>> codecs.encode(b"abc", "hex")
b'616263'
>>> import binascii
>>> binascii.hexlify(b"abc")
b'616263'
>>> import base64
>>> base64.b16encode(b"abc")
b'616263'
>>> hex(int.from_bytes(b"abc", "big"))
'0x616263'
>>> hex(int.from_bytes(b"abc", "little"))
'0x636261'

Thus, the underlying purpose of this proposal is to provide a single "more obvious way to do it". As per the recent discussion on python-ideas, the point where that is most useful is in debugging output.

However, rather than a new method on bytes/bytearray/memoryview for this, I instead suggest it would be appropriate to extend the default handling of the "x" and "X" format characters to accept arbitrary bytes-like objects. The processing of these characters would be as follows:

"x": display a-f as lowercase digits
"X": display A-F as uppercase digits
"#": includes 0x prefix
".precision": chunks output, placing a space after every <precision> bytes
",": uses a comma as the separator, rather than a space

Output order would match binascii.hexlify()

Examples:

format(b"xyz", "x") -> '78797a'
format(b"xyz", "X") -> '78797A'
format(b"xyz", "#x") -> '0x78797a'

format(b"xyz", ".1x") -> '78 79 7a'
format(b"abcdwxyz", ".4x") -> '61626364 7778797a'
format(b"abcdwxyz", "#.4x") -> '0x61626364 0x7778797a'

format(b"xyz", ",.1x") -> '78,79,7a'
format(b"abcdwxyz", ",.4x") -> '61626364,7778797a'
format(b"abcdwxyz", "#,.4x") -> '0x61626364,0x7778797a'

This approach makes it easy to inspect binary data, with the ability to inject regular spaces or commas to improved readability. Those are the basic features needed to support debugging.

Anything more complicated than that, and we're starting to want something more like the struct module.
History
Date User Action Args
2014-09-10 23:04:07ncoghlansetrecipients: + ncoghlan, georg.brandl, rhettinger, terry.reedy, mark.dickinson, pitrou, vstinner, gotgenes, christian.heimes, eric.araujo, Arfrever, wiggin15, martin.panter, serhiy.storchaka, hct
2014-09-10 23:04:07ncoghlansetmessageid: <1410390247.33.0.30641506895.issue9951@psf.upfronthosting.co.za>
2014-09-10 23:04:07ncoghlanlinkissue9951 messages
2014-09-10 23:04:07ncoghlancreate