Robert
That's very clear, thanks. Reinteract has a feature that can sort of do
this. If you import a module that has a function called
'__reinteract_wrap__', Reinteract will give it the chance to format the
output. So if you create a module called formatfloat.py, for example,
that has the content:
----------
def __reinteract_wrap__(value):
if isinstance(value, float):
return round(value, 2)
return None
-----------
Then in a worksheet you can do:
>>> 0.12345
0.12345
>>> import formatfloat
>>> 0.12345
0.12
There are a few problems that I can see with this method.
1) Floats that are part of another data structure (lists, dicts, etc)
will not be so formatted. You could fix that by creating a more
extensive __reinteract_wrap__ function that will construct a new
structure with rounded numbers, but this could be a pain. From your
original email, it sounded like you had a way to do this formatting in
the standard interpreter. If so, could you share that with us? It
might yield another approach that could deal with this problem more
elegantly.
2) By rounding, you don't get the same result as with the format string:
>>> 0.1
0.1
>>> print "%0.2f" % 0.1
0.10
What I wanted to do was have the first return statement give '"%0.2f" %
value'. But then Reinteract treats it as a string, and you'd get
>>> 0.1
'0.10'
which is probably not what you want. General question: Should
Reinteract not call 'repr' on the result of __reinteract_wrap__ if it is
a string? This would make it easier to produce text output.
Hope that helps,
Robert
And I'm an idiot. The easy way to get the text output you want is just
to make your own class with a __repr__ method. See below for a better
solution.
Robert
---------- formatfloat.py ----------
def __reinteract_wrap__(value):
if isinstance(value, float):
return fixed_prec(value)
return None
class fixed_prec(float):
def __repr__(self):
return "%0.2f" % self