[Python-3000] More PEP 3101 changes incoming

Adam Olsen rhamph at gmail.com
Sat Aug 4 07:03:14 CEST 2007


On 8/3/07, Talin <talin at acm.org> wrote:
> Ron Adam wrote:
> > After a fair amount of experimenting today, I think I've found a nice
> > middle ground that meets some of what both you and Guido are looking
> > for. (And a bit my own preference too.)
>> First off, thank you very much for taking the time to think about this
> in such detail. There are a lot of good ideas here.
>> What's missing, however, is a description of how all of this interacts
> with the __format__ hook. The problem we are facing right now is
> sometimes we want to override the __format__ hook and sometimes we
> don't. Right now, the model that we want seems to be:
>> 1) High precedence type coercion, i.e. 'r', which bypasses __format__.
> 2) Check for __format__, and let it interpret the format specifier.
> 3) Regular type coercion, i.e. 'd', 'f' and so on.
> 4) Regular formatting based on type.

Why not let __format__ return NotImplemented as meaning "use a
fallback". E.g., 'd' would fall back to obj.__index__, 'r' to
repr(obj), etc. You'd then have code like this:
class float:
 def __format__(self, type, ...):
 if type == 'f':
 return formatted float
 else:
 return NotImplemented
class MyFloat:
 def __format__(self, type, ...):
 if type == 'D':
 return custom format
 else:
 return float(self).__format__(type, ...)
class Decimal:
 def __format__(self, type, ...):
 if type == 'f':
 return formatted similar to float
 else:
 return NotImplemented
def handle_format(obj, type, ...):
 if hasattr(obj, '__format__'):
 s = obj.__format__(type, ...)
 else:
 s = NotImplemented
 if s is NotImplemented:
 if type == 'f':
 s = float(obj).__format__(type, ...)
 elif type == 'd':
 s = operator.index(obj).__format__(type, ...)
 elif type == 'r':
 s = repr(obj)
 elif type == 's':
 s = str(obj)
 else:
 raise ValueError("Unsupported format type")
 return s
-- 
Adam Olsen, aka Rhamphoryncus


More information about the Python-3000 mailing list

AltStyle によって変換されたページ (->オリジナル) /