Message 99847 - Python tracker (original) (raw)

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 "", line 1, in 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.