The first approach to this problem might be just try
it:
class MyIntegerTenClass: def __int__(self): return 10 def __str__(self): return 'ten' def __format__(self, format_spec): try: s = format(str(self), format_spec) except ValueError: s = format(int(self), format_spec) return s
If MyIntegerTenClass
can be inserted into a format string as a string, it will. If not, it will be converted to int and resubmitted to format
.
>>> print '{0}, {0:s}, {0:d}, {0:02X}, {0:f}'.format(ten) ten, ten, 10, 0A, 10.000000
If you want the default view to be 10
instead of ten
, you only need to replace the conversion strings:
def __format__(self, format_spec): try: s = format(int(self), format_spec) except ValueError: s = format(str(self), format_spec) return s
Test output:
>>> print '{0}, {0:s}, {0:d}, {0:02X}, {0:f}'.format(ten) 10, ten, 10, 0A, 10.000000
As a complement, I do not believe that you can get the right behavior without defining __format__
; however, you can develop a more complex approach using the Formatter
object. However, I think the exception-based approach gives you many built-in functions for free.