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

Michael Urman murman at gmail.com
Thu Jan 16 17:33:32 CET 2014

On Thu, Jan 16, 2014 at 8:45 AM, Brett Cannon <brett at python.org> wrote:
> Fine, if you're worried about bytes.format() overstepping by implicitly
> calling str.encode() on the return value of __format__() then you will need
> __bytes__format__() to get equivalent support.

Could we just re-use PEP-3101's note (easily updated for Python 3):

    Note for Python 2.x: The 'format_spec' argument will be either
    a string object or a unicode object, depending on the type of the
    original format string.  The __format__ method should test the type
    of the specifiers parameter to determine whether to return a string or
    unicode object.  It is the responsibility of the __format__ method
    to return an object of the proper type.

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.)

More information about the Python-Dev mailing list