[Python-3000] More PEP 3101 changes incoming
Eric Smith
eric+python-dev at trueblade.com
Mon Aug 13 04:37:54 CEST 2007
Eric V. Smith wrote:
> Right. Your "if" test is my is_float_specifier function. The problem
> is that this needs to be shared between int and float and string, and
> anything else (maybe decimal?) that can be converted to a float. Maybe
> we should make is_float_specifier a classmethod of float[1], so that
> int's __format__ (and also string's __format__) could say:
>
> if float.is_float_specifier(spec):
> return float(self).__format__(spec)
>
> And float's __format__ function could do all of the specifier testing,
> for types it knows to convert itself to, and then say:
As I've begun implementing this, I think we really do need these
is_XXX_specifier functions.
Say I create a new int-like class, not derived from int, named MyInt.
And I want to use it like an int, maybe to print it as a hex number:
i = MyInt()
"{0:x}".format(i)
In order for me to write the __format__ function in MyInt, I have to
know if the specifier is in fact an int specifier. Rather than put this
specifier checking logic into every class that wants to convert itself
to an int, we could centralize it in a class method int.is_int_specifier
(or maybe int.is_specifier):
class MyInt:
def __format__(self, spec):
if int.is_int_specifier(spec):
return int(self).__format__(spec)
return "MyInt instance with custom specifier " + spec
def __int__(self):
return <some local state>
The problem with this logic is that every class that implements __int__
would probably want to contains this same logic.
Maybe we want to move this into unicode.format, and say that any class
that implements __int__ automatically will participate in a conversion
for a specifier that looks like an int specifier. Of course the same
logic would exist for float and maybe string. Then we wouldn't need a
public int.is_int_specifier.
The disadvantage of this approach is that if you do implement __int__,
you're restricted in what format specifiers your __format__ method will
ever be called with. You're restricted from using a specifier that
starts with d, x, etc. That argues for making every __format__ method
implement this test itself, only if it wants to. Which means we would
want to have int.is_int_specifier.
Thoughts?
Eric.
More information about the Python-3000
mailing list