[Python-Dev] PEP 461 - Adding % and {} formatting to bytes

Neil Schemenauer nas at arctrix.com
Thu Jan 16 18:13:43 CET 2014


Michael Urman <murman at gmail.com> wrote:
> If __format__ receives a format_spec of type bytes, it should return
> bytes. For such cases on objects that cannot support bytes (i.e. for
> str), it can raise. This appears to avoid the need for additional
> methods. (As does Nick's proposal of leaving it out for now.)

That's an interesting idea.  I proposed __ascii__ as a analogous
method to __format__ for bytes formatting and to have
%-interpolation use it.  However, overloading __format__ based on
the type of the argument could work.

I see with Python 3:

    >>> (1).__format__(b'')
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: must be str, not bytes

A TypeError exception is what we want if the object does not support
bytes formatting.  Some possible problems:

- It could be hard to provide a helpful exception message since it
  is generated inside the __format__ method rather than inside the
  bytes.__mod__ method (in the case of a missing __ascii__ method).
  The most common error will be using a str object and so we could
  modify the __format__ method of str to provide a nice hint (use
  encode()).

- Is there some risk that an object will unwittingly implement a
  __format__ method that unintentionally accepts a bytes argument?
  That requires some investigation.



More information about the Python-Dev mailing list