[Python-Dev] PEP 461 - Adding % and {} formatting to bytes
Neil Schemenauer
nas at arctrix.com
Wed Jan 15 22:24:27 CET 2014
Glenn Linderman <v+python at g.nevcal.com> wrote:
> On 1/15/2014 7:52 AM, Eric V. Smith wrote:
>> Either that, or we're back to encoding the result of __format__ and
>> accepting that sometimes it might throw errors, depending on the values
>> being passed into format().
That would take us back to Python 2 hell. Please no. I don't like
checking for types either, we should have a special method.
> Looks like you need to invent __formatb__ to produce only ASCII.
> Objects that have __formatb__ can be formatted by bytes.format. To
> avoid coding, it could be possible that __formatb__ might be a callable
> in which case it is called to get the result, or not a callable, in
> which case one calls __format__ and converts the result to ASCII,
> __formatb__ just indicating a guarantee that only ASCII will result.
Just do:
def __formatb__(self, spec):
return MyClass.__format__(self, spec).encode('ascii')
Note that I think it is better to explicitly use the __format__
method rather than using self.__format__. My reasoning is that a
subclass might implement a __format__ that returns non-ASCII
characters.
We don't need a special bytes version of __str__ since the
%-operator can call __formatb__ with the correct format spec.
Neil
More information about the Python-Dev
mailing list