[Python-Dev] RFC: PEP 460: Add bytes % args and bytes.format(args) to Python 3.5
Stephen J. Turnbull
stephen at xemacs.org
Thu Jan 9 05:53:02 CET 2014
Antoine Pitrou writes:
> However, interpolating a bytes object isn't out of place, and it is
> what a minimal "formatting" primitive could do.
Something like this?
# VERY incomplete pseudo-code
# new method
# fmtstring has syntax of .format method's spec, maybe adding a 'B'
# for "insert Blob of bytes" spec
def format_for_wire(fmtstring, args, encoding='utf-8', errors='strict'):
result = b''
# gotta go to a meeting, exercise for reader :-(
parts = zip_specs_and_args(fmtstring, args)
for spec, arg in parts:
if spec == 'B' and isinstance(arg, bytes):
result += arg
partial = format(spec, arg)
result += partial.encode(encoding=encoding, errors=errors)
Maybe format_to_bytes is a more accurate name.
I have no idea how to do this for %-formatting though. :-(
And I have the sneaking suspicion that it *can't* be this easy. :-(
Can it? :-)
More information about the Python-Dev