Eric V. Smith added the comment:
As David says, the change from:
ValueError: Unknown format code 'f' for object of type 'str'
to:
TypeError: non-empty format string passed to object.__format__
is quite intentional.
Let me address the differences between %-formatting and __format__-based
formatting. In these examples, let's say you're trying to format an object
o=MyType(whatever).
With your '%f' example, you're saying "please convert o to a float, and then
format and print the result". The %-formatting code knows a priori that the
type must be converted to a float.
With your {:f} example, you're saying "please call o.__format__('f'), and print
the result". Nowhere is there any logic that says "well, f must mean that o
must be converted to a float". The decision on conversion (if any) is left to
MyType.__format__, as are all other formatting decisions. You could write
something like:
class MyType(object):
def __format__(self, fmt):
if fmt.endswith('f'):
return float(self.func()).__format__(fmt)
elif fmt.endswith('d'):
return int(self.func()).__format__(fmt)
else:
return str(self.func()).__format__(fmt)
def __init__(self, func):
self.func = func
print(format(MyType(lambda: 3), '.12f')) # produces "3.000000000000"
print(format(MyType(lambda: 3), '05d')) # produces "00003"
print(format(MyType(lambda: 3), '*^10s')) # produces "****3*****"
Note that %-formatting only supports a fixed and limited number of types:
basically int, float, and str. It cannot support new type of objects with their
own format strings.
With __format__-formatting, every type can specify how it wants to be
formatted, and can specify its own format language. For example, datetime
supports a rich formatting language (based on strftime).
----------
nosy: +eric.smith
_______________________________________
Python tracker <[email protected]>
<http://bugs.python.org/issue23479>
_______________________________________
_______________________________________________
Python-bugs-list mailing list
Unsubscribe:
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com