[issue3982] support .format for bytes

Terry J. Reedy report at bugs.python.org
Wed Jan 23 08:29:08 CET 2013


Terry J. Reedy added the comment:

After re-reading everything, I have somewhat changed my mind on this proposal. Perhaps 3.0 threw out too much, making it overly difficult to do some things that were to easy in 2.x and to write cross-version code.

String formatting converts all arguments to strings, using str as the default converter, but gives particular attention to formatting ints and floats. It then interpolates the resulting strings into the template string. Until msg180430, posted just half a day ago, I did not see a coherent idea of what bytes.format should be. The main problem is that there is no general bytes converter equivalent to str. I believe this is the core reason bytes.format was eliminated in 3.0.

Much of the discussion here and elsewhere has been about str.format + additions, where the additions would accommodate various possible conversions. But I now see that this was trying to do too much. Guido's subset proposal cuts this all out by proposing to only convert ints and floats as done in 2.x. So bytes.format would only convert ints and floats and otherwise would interpolate bytes into a bytes template. This should cover a large fraction of use cases. The user would be responsible for converting anything else, or converting ints and floats otherwise, with explicit calls to bytes, str.encode, struct.pack, or custom functions*..

I believe only two changes are needed to the specification of str.format, other than the obvious things like prefixing strings with 'b' and changing 'fill character' to 'fill byte'.  Since general conversion would not be be done, the '! conversion' field would be eliminated. In the format specifier, the default 's' would mean that the corresponding argument must be a bytes objects, rather than any object converted by str.

# possible portability function for 'other' classes:

if py2: strb = str
else:
  def strb(ob): return str(ob).encode()

----------

_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue3982>
_______________________________________


More information about the Python-bugs-list mailing list