[Python-Dev] 3.1 and 2.7 break format() when used with complex (sometimes)
Eric Smith
eric at trueblade.com
Mon Feb 22 21:36:33 CET 2010
Eric Smith wrote:
> This code works on 2.6 and 3.0:
> >>> format(1+1j, '10s')
> '(1+1j) '
>
> That's because format ends up calling object.__format__ because complex
> doesn't have its own __format__. Then object.__format__ calls str(self)
> which returns '(1+1j) '. So the original call basically turns into
> "format('(1+1j) ', '10s')".
Guido pointed out this should have been:
"""That's because format ends up calling object.__format__ because
complex doesn't have its own __format__. Then object.__format__ calls
str(self) which returns '(1+1j)'. So the original call basically turns
into "format('(1+1j)', '10s')".""" (I had inserted the spaces added by
str.__format__ too early.)
We discussed this at the sprint.
We agreed that we'd just allow this specific issue with complex
formatting to possibly break existing uses in 2.7, as it did in 3.1.
While that's unfortunate, it's better than the alternatives.
The root cause of this problem is object.__format__, which is basically:
def __format__(self, fmt):
return str(self).__format__(fmt)
So here we're changing the type of the object (to str) but still keeping
the same format string. That doesn't make any sense: the format string
is type specific. I think the correct thing to do here is to make it an
error if fmt is non-empty. In 2.7 and 3.2 I can make this a
PendingDeprecationWarning, then in 3.3 a DeprecationWarning, and finally
make it an error in 3.4.
Eric.
More information about the Python-Dev
mailing list