New submission from Eric Smith <e...@trueblade.com>:

Background:

format(obj, fmt) eventually calls object.__format__(obj, fmt) if obj (or one of 
its bases) does not implement __format__. The behavior of object.__format__ is 
basically:

def __format__(self, fmt):
    return str(self).__format__(fmt)

So the caller of format() thought they were passing in a format string specific 
to obj, but it is interpreted as a format string for str.

This is not correct, or at least confusing. The format string is supposed to be 
type specific. However in this case the object is being changed (to type str), 
but the format string which was to be applied to its original type is now being 
passed to str.

This is an actual problem that occurred in the migration from 3.0 -> 3.1 and 
from 2.6 -> 2.7 with complex. In the earlier versions, complex did not have a 
__format__ method, but it does in the latter versions. So this code:
>>> format(1+1j, '10s')
'(1+1j)    '
worked in 2.6 and 3.0, but gives an error in 2.7 and 3.1:
>>> format(1+1j, '10s')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: Unknown format code 's' for object of type 'complex'

Proposal:
object.__format__ should give an error if a non-empty format string is 
specified. In 2.7 and 3.2 make this a PendingDeprecationWarning, in 3.3 make it 
a DeprecationWarning, and in 3.4 make it an error.

Modify the documentation to make this behavior clear, and let the user know 
that if they want this behavior they should say:

format(str(obj), '10s')

or the equivalent:

"{0!s:10}".format(obj)

That is, the conversion to str should be explicit.

----------
assignee: eric.smith
components: Interpreter Core
messages: 99847
nosy: eric.smith
priority: normal
severity: normal
stage: needs patch
status: open
title: object.__format__ should reject format strings
type: behavior
versions: Python 2.7, Python 3.2

_______________________________________
Python tracker <rep...@bugs.python.org>
<http://bugs.python.org/issue7994>
_______________________________________
_______________________________________________
Python-bugs-list mailing list
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com

Reply via email to