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

Ethan Furman ethan at stoneleaf.us
Thu Jan 16 19:55:47 CET 2014


On 01/16/2014 10:30 AM, Eric V. Smith wrote:
> On 01/16/2014 11:23 AM, Ethan Furman wrote:
>> On 01/16/2014 06:45 AM, Brett Cannon wrote:
>>>
>>> But that's **only** because the numeric types choose
>>> to as part of their __format__() implementation; it is
>>> not inherent to str.format().
>>
>> As I understand it, str.format will call the object's __format__.  So,
>> for example, if I say:
>>
>>    u'the value is: %d' % myNum(17)
>>
>> then it will be myNum.__format__ that gets called, not int.__format__;
>> this is precisely what we don't want, since can't know that myNum is
>> only going to return ASCII characters.
>
> "Magic" methods, including __format__, are called on the type, not the
> instance.

Yes, that's why I said `myNum(17)` and not `myNum`.


>> This is why I would have bytes.__format__, as part of its parsing, call
>> int, index, or float depending on the format code; so the above example
>> would have bytes.__format__ calling int() on myNum(17), at which point
>> we either have an int type or an exception was raised because myNum
>> isn't really an integer.  Once we have an int, whose format we know and
>> trust, then we can call its __format__ and proceed from there.
>>
>> On the flip side, if myNum does define it's own __format__, it will not
>> be called by bytes.format, and perhaps that is another good reason for
>> bytes to only support %-interpolation and not format?
>
> For the first iteration of bytes.format(), I think we should just
> support the exact types of int, float, and bytes. It will call the
> type's__format__ (with the object as "self") and encode the result to
> ASCII. For the stated use case of 2.x compatibility, I suspect this will
> cover > 90% of the uses in real code. If we find there are cases where
> real code needs additional types supported, we can consider adding
> __format_ascii__ (or whatever name we cook up).

That can certainly be our fallback position if we can't decide now how we want to handle int and float subclasses.

--
~Ethan~


More information about the Python-Dev mailing list