[Python-ideas] %-formatting with Decimals

Andrew Barnert abarnert at yahoo.com
Wed Mar 12 01:45:38 CET 2014


On Mar 11, 2014, at 15:49, Oscar Benjamin <oscar.j.benjamin at gmail.com> wrote:

> On 11 March 2014 21:58, Ethan Furman <ethan at stoneleaf.us> wrote:
>> On 03/11/2014 02:51 PM, random832 at fastmail.us wrote:
>>> 
>>> The bug to which I was referring involves not calling __format__ on
>>> whatever object is passed in as str.format does - Decimal not being
>>> float is no impediment to str.format and Decimal.__format__ accepting
>>> the same format strings that float.__format__ does.
>> 
>> That is not a bug.  str.__mod__ is not documented as calling an object's
>> __format__ method, and indeed it does not.
> 
> Instead it calls float on the object:
> 
>>>> class A:
> ...   def __float__(self):
> ...     print('__float__ called')
> ...
>>>> '%f' % A()
> __float__ called
> Traceback (most recent call last):
>  File "<stdin>", line 1, in <module>
> TypeError: nb_float should return float object
> 
> There's no mention of that anywhere in the docs though:
> http://docs.python.org/3.4/library/stdtypes.html#printf-style-string-formatting

I wouldn't expect it to mention that it calls the __float__ method (much less the nb_float C slot), because it doesn't.

It converts to float in the normal way, by calling the float constructor or it's C equivalent. And the docs for float say pretty clearly that "For a general Python object" (that is, not a string or a float), "float(x) delegates to x.__float__()".

Maybe section 4.7.2 could be more explicit about the fact that the conversion type specifies a conversion to the appropriate type (int, float, or str)?

> There's also no mention of this in the decimal docs.

Why should there be? Neither printf-style string formatting nor the float constructor have anything to do with decimals.


More information about the Python-ideas mailing list