[Python-3000] More PEP 3101 changes incoming

Greg Ewing greg.ewing at canterbury.ac.nz
Sat Aug 11 03:48:11 CEST 2007


Eric Smith wrote:
> 1: "".format() ... understands which 
> types can be converted to other types, and does the conversions.
> 
> 2: each type's __format__ function understands how to convert to some 
> subset of all types (int can convert to float and decimal, for example).
> 
> The problem with approach 2 is that there's logic in 
> int.__format__() that understands float.__format__() specifiers, and 
> vice-versa.  At least with approach 1, all of this logic is in one place.

Whereas the problem with approach 1 is that it's not
extensible. You can't add new types with new format
specifiers that can be interconverted.

I don't think the logic needs to be complicated. As
long as the format spec syntaxes are chosen sensibly,
it's not necessary for e.g. int.__format__ to be able
to parse float's format specs, only to recognise when
it's got one. That could be as simple as

   if spec[:1] in 'efg':
     return float(self).__format__(spec)

> This implies that string and repr specifiers are discernible across all 
> types, and int and float specifiers are unique amongst themselves.

Another advantage of letting the __format__ methods
handle it is that a given type *can* handle another
type's format spec itself if it wants. E.g. if float
has some way of handling the 'd' format that's
considered better than converting to int first, then
it can do that.

--
Greg


More information about the Python-3000 mailing list