No, there is no way to overload repr()
. The format for floats is hardcoded in the C source code.
The float_repr()
function calls a helper function with the 'r'
formatter, which eventually calls a utility function that hardcodes the format to what comes down to format(float, '.16g')
.
You could subclass float
, but to only do that for representing values (especially in a larger structure) is overkill. This is where repr
(reprlib
in Python 3) comes in; that library is designed to print useful representations of arbitrary data structures, and letting you hook into printing specific types in that structure.
You could use the repr
module by subclassing repr.Repr()
, providing a repr_float()
method to handle floats:
try: # Python 3
import reprlib
except ImportError: # Python 2
import repr as reprlib
class FloatRepr(reprlib.Repr):
def repr_float(self, value, level):
return format(value, '.4f')
print(FloatRepr().repr(object_to_represent))
Demo:
>>> import random
>>> import reprlib
>>> class FloatRepr(reprlib.Repr):
... def repr_float(self, value, level):
... return format(value, '.4f')
...
>>> print(FloatRepr().repr([random.random() for _ in range(5)]))
[0.5613, 0.9042, 0.3891, 0.7396, 0.0140]
You may want to set the max*
attributes on your subclass to influence how many values are printed per container type.